﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Threading;
using System.Drawing.Drawing2D;
using System.Text.RegularExpressions;
using chatSDKApp.Forms;
using System.Collections;
using System.Threading.Tasks;
using System.IO;
using System.Text;
using System.Net;
using System.Drawing.Imaging;
using chatSDKApp.Forms.ChatRoom;
using System.Reflection;
using NAudio.Wave;
using Shell32;
using DevComponents.DotNetBar;
using Newtonsoft.Json;
using System.Configuration;
using AgoraChat;

namespace chatSDKApp.ChatRoom
{
    public partial class FrmChatRoom : Form, IChatManagerDelegate, IConnectionDelegate 
    {
        #region Chat   
        //创建一个委托，是为访问TextBox控件服务的。
        public delegate void UpdateTxt(string t, string c);
        //定义一个委托变量
        public event UpdateTxt updateTxt;
        //配置文件获取KEY
        //private static readonly string APPKEY = "1177220311110811#fhcloud";//测试环境Key
        //private static readonly string APPKEY = BaseConfig.Instance.DispatchConfig.IMAppKey;
        private readonly static string APPKEY = ConfigurationManager.AppSettings["IMAppKey"].ToString().Trim();
        //定义好友列表消息提示集合
        private static Hashtable ht = new Hashtable();
        //定义群组列表消息提示集合
        private static Hashtable htGroup = new Hashtable();
        //定义存放好友列表名List
        private static List<string> friend_list = new List<string>();
        //定义全局获取的好友个数
        private static int friends_Count = 0;
        //好友列表的ID 和 Name字典
        private static  Dictionary<string, string> dicFriendNames = new Dictionary<string, string>();

        //记录未读消息的好友或者群聊
        public static Dictionary<string, string> dicUnread = new Dictionary<string, string>();
        //群聊
        private static  Dictionary<string, AgoraChat.Group> dicGroup = new Dictionary<string, AgoraChat.Group>();
        //群聊id集合
        private static  Dictionary<int, string> dicGroupIds = new Dictionary<int, string>();
        //群聊用户成员信息
        public static Dictionary<string,Dictionary<string,UserInfo>> dicGroupMembers = new Dictionary<string, Dictionary<string,UserInfo>>();

        //当前会话对象
        private static string currentChatUser = "";
        //存放chanel和user键值对
        private static Dictionary<int, string> dic = new Dictionary<int, string>();
        //当前用户名
        private static string UserName;
        //设置缓存路径
        private static string download_file_path = Directory.GetCurrentDirectory() + @"\ImagesCache\download\";
        //收到消息的图片地址
        static string receiveImagePath = "";
        //收到消息的语音文件地址
        static string receiveVoicePath = "";
        //累计上翻页次数
        static int up_count = 1;//初始已经显示了最新一页
        //累计可下翻页次数,负数
        static int down_count = 0;
        //存放聊天记录
        static List<AgoraChat.Message> Totallist = new List<AgoraChat.Message>();
        //统计聊天记录实际条数
        static int total_count = 0;
        //有消息来，打开窗体时，就不打开默认第一位好友
        static bool load_f = true;
        //记录好友列表的点击时间
        private DateTime clickTime = DateTime.Now;

        int limt, climt, set_x, cset_x; //滚动位置最大值和固定的左右的位置
        int Fmx, Fmy; //主窗口坐标
        bool mouse_Press = false, cmouse_Press = false; //鼠标按下
        bool mouse_Wheel = true, cmouse_Wheel = true; //鼠标滑轮事件
        Point mouseOff, cmouseOff; //存放当前鼠标位置
        string[,,] palte = new string[1, 10, 3]; //栏目，定义时根据好友个数赋值三维数组的个数    
        string[,,] groupPalte = new string[1, 10, 4]; //栏目，定义时根据好友个数赋值三维数组的个数    
        public PicRichTextBox Rich_Edit; //编辑文字框
        static int Chanel = -1; //当前好友或者群聊列表下标值
        static int OldChanel = -1; //前好友或者群聊列表下标值
        static int Linewidth, Lineheight; //显示对话内容容器的宽度和高度

        ContainerControl _mainHandleIntPtr = null;//该控件可以充当其他控件的容器并提供焦点管理

        private delegate void InvokeHandler();
        #endregion

        #region 外部函数

        //logo图画设置按鼠标移动窗体
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
        private static extern IntPtr CreateRoundRectRgn
           (
               int nLeftRect,
               int nTopRect,
               int nRightRect,
               int nBottomRect,
               int nWidthEllipse,
               int nHeightEllipse
            );

        [DllImport("dwmapi.dll")]
        public static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);

        [DllImport("dwmapi.dll")]
        public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);

        [DllImport("dwmapi.dll")]
        public static extern int DwmIsCompositionEnabled(ref int pfEnabled);

        private bool m_aeroEnabled;
        private const int CS_DROPSHADOW = 0x00020000;
        private const int WM_NCPAINT = 0x0085;
        #endregion

        #region 窗体
        public struct MARGINS
        {
            public int leftWidth;
            public int rightWidth;
            public int topHeight;
            public int bottomHeight;
        }
        private Panel Speac_panel;
        private Panel panel1;

        protected override CreateParams CreateParams
        {
            get
            {
                m_aeroEnabled = CheckAeroEnabled();

                CreateParams cp = base.CreateParams;
                if (!m_aeroEnabled)
                    cp.ClassStyle |= CS_DROPSHADOW;

                return cp;
            }
        }
        private bool CheckAeroEnabled()
        {
            if (Environment.OSVersion.Version.Major >= 6)
            {
                int enabled = 0;
                DwmIsCompositionEnabled(ref enabled);
                return (enabled == 1) ? true : false;
            }
            return false;
        }

        //对话框绘图
        private void Draw(Rectangle rectangle, Graphics g, int _radius, bool cusp, int orientation, Color begin_color, Color end_color)
        {
            try
            {
                int span = 2;
                //抗锯齿
                g.SmoothingMode = SmoothingMode.AntiAlias;
                //渐变填充
                LinearGradientBrush myLinearGradientBrush = new LinearGradientBrush(rectangle, begin_color, end_color, LinearGradientMode.Vertical);
                //画尖角
                if (cusp)
                {
                    if (orientation == 0)
                    {
                        span = 10;
                        PointF p1 = new PointF(rectangle.Width - 12, rectangle.Y + 10);
                        PointF p2 = new PointF(rectangle.Width - 12, rectangle.Y + 30);
                        PointF p3 = new PointF(rectangle.Width, rectangle.Y + 20);
                        PointF[] ptsArray = { p1, p2, p3 };
                        g.FillPolygon(myLinearGradientBrush, ptsArray);
                        g.FillPath(myLinearGradientBrush, DrawRoundRect(rectangle.X, rectangle.Y, rectangle.Width - span, rectangle.Height - 1, _radius));
                    }
                    else
                    if (orientation == 1)
                    {
                        span = 10;
                        PointF p1 = new PointF(12, rectangle.Y + 10);
                        PointF p2 = new PointF(12, rectangle.Y + 30);
                        PointF p3 = new PointF(0, rectangle.Y + 20);
                        PointF[] ptsArray = { p1, p2, p3 };
                        g.FillPolygon(myLinearGradientBrush, ptsArray);
                        g.FillPath(myLinearGradientBrush, DrawRoundRect(rectangle.X + span, rectangle.Y, rectangle.Width - span, rectangle.Height - 1, _radius));
                    }
                    else
                    {
                        g.FillPath(myLinearGradientBrush, DrawRoundRect(rectangle.X, rectangle.Y, rectangle.Width - span, rectangle.Height - 1, _radius));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log("Draw:", ex.Message);
            }    
        }
        public static GraphicsPath DrawRoundRect(int x, int y, int width, int height, int radius)
        {
            //四边圆角
            GraphicsPath gp = new GraphicsPath();
            gp.AddArc(x, y, radius, radius, 180, 90);
            gp.AddArc(width - radius, y, radius, radius, 270, 90);
            gp.AddArc(width - radius, height - radius, radius, radius, 0, 90);
            gp.AddArc(x, height - radius, radius, radius, 90, 90);
            gp.CloseAllFigures();
            return gp;
        }


        public FrmChatRoom(string user, string pwd, ContainerControl mainHandleIntPtr)
        {
            #region 
          
            _mainHandleIntPtr = mainHandleIntPtr;
            //消息提示
            updateTxt = new UpdateTxt(UpdateTxtMethod);

            #endregion
            InitializeComponent();
            //this.EnableGlass = false;//使用DonetBar样式

            //重新设置图标
            Icon icon = new Icon(@"Resources\apts64.ico");
            this.Icon = icon;

            //判断图片缓存路径是否存在
            if (!Directory.Exists(download_file_path))
            {
                Directory.CreateDirectory(download_file_path);
            }

            m_aeroEnabled = false; //窗体四边阴影       
            CheckForIllegalCrossThreadCalls = false;//跨线程检查

            //登录初始化
            InitSDK(user, "123456");//初始密码
            //InitSDK(user, pwd);
            //记录用户名
            UserName = user;
            Id_label.Text = "工号:" + UserName;//登录信息显示

            #region 好友列表的鼠标事件
            Chanel_panel2.MouseWheel += new MouseEventHandler(OnMouseWheel);
            cp2.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Chn_2.MouseWheel += new MouseEventHandler(OnMouseWheel);
            CNum2.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Chanel_panel4.MouseWheel += new MouseEventHandler(OnMouseWheel);
            cp4.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Chanel_panel4.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Chn_4.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Left_panel.MouseWheel += new MouseEventHandler(OnMouseWheel);
   
            Chanel2_Info.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Chanel3_Info.MouseWheel += new MouseEventHandler(OnMouseWheel);
            //Chanel4_Info.MouseWheel += new MouseEventHandler(OnMouseWheel);
            #endregion

            #region 控件其他属性设置
            //显示对话内容框鼠标事件
            Showinfo_panel.MouseWheel += new MouseEventHandler(c_OnMouseWheel);

            //滚动条位置定义
            set_x = ScrollHard_panel.Location.X; //固定左右位置为当前位置
            cset_x = TakeScrollHard_panel.Location.X; //固定左右位置为当前位置

            //左侧边y滚动条
            limt = ScrollBar_panel.Height - ScrollHard_panel.Height; //滚动最大高度
            ScrollHard_panel.Location = new Point(set_x, Top_panel.Height); //先将位置设置到最顶

            //右侧边y滚动条
            climt = -TakeScrollHard_panel.Height;
            TakeScrollHard_panel.Location = new Point(cset_x, 0); //先将位置设置到最顶

            //信息编辑框属性
            Rich_Edit = new PicRichTextBox();
            Rich_Edit.Dock = DockStyle.Fill;
            Rich_Edit.BackColor = Color.FromArgb(213, 224, 230);
            Rich_Edit.BorderStyle = BorderStyle.None;
            Rich_Edit.ScrollBars = RichTextBoxScrollBars.None;
            Rich_Edit.TextChanged += new EventHandler(RichEdit_TextChanged);//文本框聚焦
            Rich_Edit.KeyUp += new KeyEventHandler(Rich_Edit_Enter);//注册回车监听
            Edit_panel.Controls.Add(Rich_Edit);
            #endregion
          
        }

        #region 计算容器高度和滑轮高度

        /// <summary>
        /// 左侧好友列表部分容器的位置，以及滑轮是否可用
        /// </summary>
        private void Calc_Scroll()
        {
            int scr = 0;

            if (Top_panel.Visible == true)
            {
                scr += Top_panel.Height;
            }
            //好友
            if (Chanel2_Info.Visible == true)
            {
                scr += Chanel2_Info.Height;
            }
            if (Chanel3_Info.Visible == true)
            {
                scr += Chanel3_Info.Height;
            }
            scr += Chanel_panel2.Height + Chanel_panel4.Height;
            if ((scr - Left_panel.Height) <= 0)
            {
                mouse_Wheel = false;
                Content_panel.Top = 105;//上留出头像位置
                ScrollHard_panel.Location = new Point(set_x, Top_panel.Height);
            }
            else
            {
                mouse_Wheel = true;
            }
        }

        /// <summary>
        /// 右侧聊天记录界面部分，容器的位置，以及滑轮是否可用
        /// </summary>
        private void cCalc_Scroll()
        {
            if ((Showinfo_panel.Height - Takeconter_panel.Height) <= 0)
            //if ((Showinfo_panel.Height - TakeScrollHard_panel.Location.Y) <= 0) 
            {
                cmouse_Wheel = false;
                Showinfo_panel.Top = 0;
                TakeScrollHard_panel.Location = new Point(cset_x, 0);
            }
            else
            {
                cmouse_Wheel = true;
            }
        }

        /// <summary>
        /// 聊天好友鼠标滑轮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnMouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            int set_y = 0;
            Calc_Scroll();
            if (mouse_Wheel) //是否判断鼠标滑轮
            {
                if (e.Delta > 0) //滑轮向上
                {
                    set_y = ScrollHard_panel.Location.Y - 10; //每次移动10
                    if (set_y <= 90) { set_y = 0; } //超范围;60
                }
                if (e.Delta < 0)  //滑轮向下
                {
                    set_y = ScrollHard_panel.Location.Y + 10; //每次移动10
                    if (set_y > limt) { set_y = limt; } //超范围               
                }

                ScrollHard_panel.Location = new Point(set_x, set_y); //滚动块的定位
                if (set_y == 0)
                {
                    Chanel2_Info.Top = Top_panel.Height + Chanel_panel2.Height + Chanel_panel4.Height - 90; //装内容的panel滚动显示  
                    //Chanel2_Info.Top = Top_panel.Height + Chanel_panel2.Height + Chanel_panel4.Height; //装内容的panel滚动显示  
                }
                else
                {
                    if (set_y < 15)
                    {
                        Chanel2_Info.Top = Top_panel.Height + Chanel_panel2.Height + Chanel_panel4.Height; //装内容的panel滚动显示  
                    }
                    else
                    {
                        Chanel2_Info.Top = -set_y + Top_panel.Height + Chanel_panel2.Height + Chanel_panel4.Height; //装内容的panel滚动显示  
                    }  
                }
               
            }
        }

        /// <summary>
        /// 此鼠标滑轮事件与上面固定高度鼠标滑轮事件不同，根据气泡的位置，容器高度不断变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void c_OnMouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            int set_y = 0;

            cCalc_Scroll();
            if (cmouse_Wheel) //是否判断鼠标滑轮
            {
                if (e.Delta > 0) //滑轮向上
                {
                    set_y = TakeScrollHard_panel.Location.Y - 10; //每次移动10
                    if (set_y < 0) { set_y = 0; } //超范围
                }
                if (e.Delta < 0)  //滑轮向下
                {
                    set_y = TakeScrollHard_panel.Location.Y + 10; //每次移动10
                    if (set_y > climt) { set_y = climt; } //超范围
                }

                //int set_y1 = Takeconter_panel.Height - (int)(Takeconter_panel.Height * set_y / (double)climt);
                TakeScrollHard_panel.Location = new Point(cset_x, set_y); //滚动块的定位

                int p_set = Takeconter_panel.Height - Showinfo_panel.Height + climt - set_y;
                if (p_set > 0) p_set = 0;
                Showinfo_panel.Top = p_set;
            }
        }

        #endregion

        #region 自定义滚动条鼠标事件
        private void ScrollHard_panel_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) //鼠标左键
            {
                mouseOff.Y = e.Y;  //取当前位置
                mouse_Press = true; //鼠标按下
            }
        }
        private void ScrollHard_panel_MouseUp(object sender, MouseEventArgs e)
        {
            mouse_Press = false; //鼠标放开
        }
        private void ScrollHard_panel_MouseLeave(object sender, EventArgs e)
        {
            mouse_Wheel = false; //滑轮不可用
        }
        private void ScrollHard_panel_MouseMove(object sender, MouseEventArgs e)
        {
            Calc_Scroll();
            if (mouse_Wheel)   //可以用滑轮
            {
                if (mouse_Press) //鼠标按下状态
                {
                    int set_y = ScrollHard_panel.Top + e.Y - mouseOff.Y; //计算当前纵向坐标
                    if (set_y < 0) { set_y = 0; } //超范围
                    else if (set_y > limt) { set_y = limt; } //超范围
                    else { ScrollHard_panel.Location = new Point(set_x, set_y); } //滚动块的定位
                    Content_panel.Top = -set_y; //装内容的panel滚动显示
                }
            }
        }

        private void TakeScrollHard_panel_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) //鼠标左键
            {
                cmouseOff.Y = e.Y;  //取当前位置
                cmouse_Press = true; //鼠标按下
            }
        }

        private void TakeScrollHard_panel_MouseUp(object sender, MouseEventArgs e)
        {
            cmouse_Press = false; //鼠标放开
        }
        private void TakeScrollHard_panel_MouseLeave(object sender, EventArgs e)
        {
            cmouse_Wheel = false; //滑轮不可用
        }

        private void TakeScrollHard_panel_MouseMove(object sender, MouseEventArgs e)
        {
            cCalc_Scroll();
            if (cmouse_Wheel)   //可以用滑轮
            {
                if (cmouse_Press) //鼠标按下状态
                {
                    int set_y = TakeScrollHard_panel.Top + e.Y - cmouseOff.Y; //计算当前纵向坐标
                    if (set_y < 0) { set_y = 0; } //超范围
                    else if (set_y > climt) { set_y = climt; } //超范围
                    else { TakeScrollHard_panel.Location = new Point(cset_x, set_y); } //滚动块的定位

                    int p_set = Takeconter_panel.Height - Showinfo_panel.Height + climt - set_y;
                    if (p_set > 0) p_set = 0;
                    Showinfo_panel.Top = p_set;
                }
            }
        }

        private void ScrollBar_panel_MouseMove(object sender, MouseEventArgs e)
        {
            Calc_Scroll();  //可以使用滑轮
        }
        private void ScrollBar_panel_MouseLeave(object sender, EventArgs e)
        {
            mouse_Wheel = false; //不可使用滑轮
        }
        private void ScrollBar_panel_MouseUp(object sender, MouseEventArgs e)
        {
            Calc_Scroll();
            if (mouse_Wheel)
            {
                if (e.Button == MouseButtons.Left) //鼠标左键
                {
                    int set_y = e.Y; //当前纵坐标
                    if (set_y > limt) { set_y = limt; } //超范围
                    ScrollHard_panel.Location = new Point(set_x, set_y); //滚动块定位
                    Content_panel.Top = -set_y;//装内容的panel滚动显示
                    mouse_Press = false; //鼠标为放开状态
                }
            }
        }

        private void TakeScrollBar_panel_MouseMove(object sender, MouseEventArgs e)
        {
            cCalc_Scroll();  //可以使用滑轮
        }

        private void TakeScrollBar_panel_MouseLeave(object sender, EventArgs e)
        {
            cmouse_Wheel = false; //不可使用滑轮
        }

        private void TakeScrollBar_panel_MouseUp(object sender, MouseEventArgs e)
        {
            cCalc_Scroll();
            if (cmouse_Wheel)
            {
                if (e.Button == MouseButtons.Left) //鼠标左键
                {
                    int set_y = e.Y; //当前纵坐标
                    if (set_y > climt) { set_y = climt; } //超范围
                    TakeScrollHard_panel.Location = new Point(cset_x, set_y); //滚动块定位
                    Showinfo_panel.Top = -set_y;//装内容的panel滚动显示
                    cmouse_Press = false; //鼠标为放开状态

                    int p_set = Takeconter_panel.Height - Showinfo_panel.Height + climt - set_y;
                    if (p_set > 0) p_set = 0;
                    Showinfo_panel.Top = p_set;
                }
            }
        }

        #endregion


        /// <summary>
        /// PicRichTextBox背景透明，聊天的气泡
        /// </summary>
        public class RichTextBoxEx : PicRichTextBox
        {
            protected override CreateParams CreateParams
            {
                get
                {
                    CreateParams cp = base.CreateParams;
                    cp.ExStyle |= 0x20;
                    return cp;
                }
            }
        }

        #endregion

        #region Chat 公共方法与事件

        /// <summary>
        /// 初始化登录
        /// </summary>
        /// <param name="user"></param>
        /// <param name="pwd"></param>
        public void InitSDK(string user, string pwd)
        {
            try
            {
                //记录用户名
                UserName = user;
                //初始化实例
                Options options = new Options(appKey: APPKEY);

                SDKClient.Instance.InitWithOptions(options);

                //登录
                SignIn(user, pwd);
                //开始监听
                Start();
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-InitSDK:", ex.Message);
            }

        }

        /// <summary>
        /// 监听消息
        /// </summary>
        private void Start()
        {
            // 添加监听，需在sdk 初始化后调用
            SDKClient.Instance.ChatManager.AddChatManagerDelegate(this);
            SDKClient.Instance.AddConnectionDelegate(this);

        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <param name="pwd"></param>
        private void SignIn(string user, string pwd)
        {
            SDKClient.Instance.Login(user, pwd,false, new CallBack(
                 onSuccess: () =>
                 {
                     //获取通讯录
                     GetAllContacts();
                 },
                 onError: (code, desc) =>
                 {
                     LogHelper.Log("IM登录失败:", code + ":" + desc);
                 }
             ));
        }

        #endregion

        #region 好友列表初始化

        /// <summary>
        /// 获取通讯录列表
        /// </summary>
        private void GetAllContacts()
        {
            GetFriendList();
            GetGroupList();
        }

        /// <summary>
        /// 初始化列表
        /// </summary>
        private void InitFriendsList()
        {
            #region 取消折叠好友
            //if (Chanel2_Info.Visible)
            //{
            //    Chanel2_Info.Visible = false;
            //}
            //else
            //{
            //    //清空好友列表
            //    Chanel2_Info.Controls.Clear();
            //    //重新添加好友列表
            //    Add_Palte();
            //    Chanel4_Info.Visible = false;//群聊隐藏
            //    Chanel2_Info.Visible = true;

            //    //设置好友列表背景色,仅仅供测试，每次加载模拟收到消息
            //    //Chanel2_Info.Controls[dic.Count - 1 - 0].BackColor = Color.LightSkyBlue ;
            //    //Chanel2_Info.Controls[dic.Count - 1 - 0].Controls[0].BackColor = Color.LightSkyBlue ;
            //    //Chanel2_Info.Controls[dic.Count - 1 - 0].Controls[1].BackColor = Color.LightSkyBlue ;

            //    //根据消息初始化好友列表颜色
            //    initFriendsListBgColor();
            //}
            #endregion

            #region 非折叠部分
            ////清空好友列表
            //Chanel2_Info.Controls.Clear();
            ////重新添加好友列表
            //Add_Palte();
            //Chanel2_Info.Visible = true;

            ////设置滚动条
            //limt = ScrollBar_panel.Height - ScrollHard_panel.Height; //滚动最大高度
            ////ScrollHard_panel.Location = new Point(set_x, Top_panel.Height); //先将位置设置到最顶

            ////初始化好友列表颜色
            //initFriendsListBgColor();
            #endregion

            #region 根据群组新添加部分       
            //清空好友列表
            Chanel2_Info.Controls.Clear();
            //装内容的panel滚动显示初始位置 
            Chanel2_Info.Top = Top_panel.Height + Chanel_panel2.Height + Chanel_panel4.Height - 90;
            //重新添加好友列表
            Add_Palte();
            //取消隐藏
            Chanel2_Info.Visible = true;
            //设置滚动条
            limt = ScrollBar_panel.Height - ScrollHard_panel.Height - Top_panel.Height - Chanel_panel2.Height - Chanel_panel4.Height; //滚动最大高度
            //根据消息初始化好友列表颜色
            initFriendsListBgColor();

            //勾选第一个
            //if (Chanel2_Info.Controls.Count > 0)
            //{
            //    Take_Chanel_Click((Panel)Chanel2_Info.Controls[dic.Count - 1], new EventArgs());
            //    Thread.Sleep(200);
            //}
            #endregion

            Calc_Scroll();

        }

        /// <summary>
        /// 从服务端获取好友
        /// </summary>
        private void GetFriendList()
        {
            try
            {
                SDKClient.Instance.ContactManager.GetAllContactsFromServer(new ValueCallBack<List<string>>(
              onSuccess: (list) =>
              {
                   //全局的好友列表List
                  friend_list = list.OrderBy(s=>s).ToList();
                  friends_Count = friend_list.Count;
                  getFriendsDic();
                  getUserNamesByIds();

              }, onError: (code, desc) =>
              {
                  LogHelper.Log("IM获取用户好友列表失败:", code + ":" + desc);
              }));

            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-GetAllContacts:", ex.Message);
            }
           
        }


        /// <summary>
        /// 根据ID获取姓名
        /// </summary>
        private void getUserNamesByIds()
        {
            try
            {
                //将当前用户名也添加进List
                List<string> UserList = new List<string>();
                UserList.Add(UserName);
                UserList.AddRange(friend_list);
  
                //获取UserInfo
                SDKClient.Instance.UserInfoManager.FetchUserInfoByUserId(UserList, new ValueCallBack<Dictionary<string, UserInfo>>(
                   onSuccess: (listUserInfo) =>
                   {
                       foreach (var item in listUserInfo)
                       {
                           if (!dicFriendNames.ContainsKey(item.Key))
                           {
                               dicFriendNames.Add(item.Key, item.Value.NickName);
                           }
                       }

                   }, onError: (code, desc) =>
                   {
                       LogHelper.Log("IM获取用户姓名失败:", code + ":" + desc);
                   }));
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-getUserNamesByIds:", ex.Message);
            }
           
        }

        /// <summary>
        /// 获取好友列表对应的下标键值对
        /// </summary>
        public void getFriendsDic()
        {
            try
            {
                //好友按照ID递增排序
                friend_list.Sort((x, y) => x.CompareTo(y));
                //清空字典
                dic.Clear();
                for (int i = 0; i < friends_Count; i++)
                {
                    //记录chanel和好友对应值
                    dic.Add(i, friend_list[i].ToString());
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-getFriendsDic:", ex.Message);
            }
        }
        //处理好友列表信息
        public void Get_PlateList()
        {
            #region 好友列表内容
            try
            {
                //好友按照ID递增排序
                friend_list.Sort((x, y) => x.CompareTo(y));
                //根据好友个数初始化三维数组,并确定大小
                palte = new string[1, friends_Count, 3];
                ////清空字典
                //dic.Clear();
                for (int i = 0; i < friends_Count; i++)
                {
                    //添加好友列表信息
                    palte[0, i, 0] = friend_list[i].ToString();//ID
                    palte[0, i, 1] = "";//描述
                    palte[0, i, 2] = @"Resources\BBGJ.png";//暂时统一设置一张图片

                    //记录chanel和好友对应值
                    //dic.Add(i, friend_list[i].ToString());
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-Get_PlateList:", ex.Message);
            }


            #endregion
        }

        /// <summary>
        /// 修改边框颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            ControlPaint.DrawBorder(e.Graphics,
                                        this.panel1.ClientRectangle,
                                        Color.White,
                                        0
                                        ,
                                        ButtonBorderStyle.Solid,
                                        Color.White,
                                        0
                                        ,
                                        ButtonBorderStyle.Solid,
                                        Color.Red,
                                        1
                                        ,
                                        ButtonBorderStyle.Solid,
                                        Color.White,
                                        0
                                        ,
                                        ButtonBorderStyle.Solid);
        }
        /// <summary>
        /// 添加好友信息Chanel2_Info
        /// </summary>
        private void Add_Palte()
        {
            try
            {
                Get_PlateList();
                for (int t = 0; t > -1; t--)
                {
                    if (friends_Count > 0)
                    {
                        for (int i = friends_Count - 1; i > -1; i--)
                        {
                            if (palte[t, i, 2] != "" && palte[t, i, 2] != null)  //头像图片地址
                            {
                                Panel Take_Chanel = new Panel();
                                //Take_Chanel.Paint += new System.Windows.Forms.PaintEventHandler(panel1_Paint);
                                //设置Take_Chanel的下边界和颜色，方便分割
                                PictureBox Pic_info = new PictureBox();
                                Label Name_Info = new Label();
                                Label Message_Flag = new Label();

                                Pic_info.Size = new Size(40, 40);
                                Pic_info.Image = Image.FromFile(palte[t, i, 2]);
                                Image image = Pic_info.Image;
                                //取消椭圆头像
                                //Image newImage = CutEllipse(image, new Rectangle(0, 0, 100, 100), new Size(40, 40));
                                Pic_info.Image = image;
                                Pic_info.Location = new Point(0, 0);
                                Pic_info.Cursor = Cursors.Hand;
                                Pic_info.Tag = ":Take:" + t + ":User:" + i;
                                Take_Chanel.Controls.Add(Pic_info);

                                Name_Info.Size = new Size(85, 25);
                                Name_Info.Font = new Font("微软雅黑", 9);
                                Name_Info.ForeColor = Color.SteelBlue;
                                //Name_Info.Text = palte[t, i, 0];
                                if (string.IsNullOrWhiteSpace(dicFriendNames[palte[t, i, 0]].ToString()))
                                {
                                    Name_Info.Text = palte[t, i, 0];
                                }
                                else
                                {
                                    //Name_Info.Text = palte[t, i, 0] + "-" + dicFriendNames[palte[t, i, 0]].ToString();
                                    Name_Info.Text =  dicFriendNames[palte[t, i, 0]].ToString();
                                }
                               
                                Name_Info.Location = new Point(65, 15);//昵称坐标位置
                                Name_Info.Tag = ":Take:" + t + ":User:" + i;
                                Take_Chanel.Controls.Add(Name_Info);

                                //消息红点
                                Message_Flag.Size = new Size(25, 25);
                                Message_Flag.Font = new Font("微软雅黑", 14);
                                Message_Flag.Text = "";//圆点
                                //Message_Flag.Text = "●";//圆点

                                Message_Flag.Location = new Point(150, 12);
                                Message_Flag.TextAlign = ContentAlignment.MiddleCenter;
                                Message_Flag.Tag = "Message_Flag";
                                Take_Chanel.Controls.Add(Message_Flag);

                                Take_Chanel.Height = 40;
                                Take_Chanel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 0);
                                Take_Chanel.BackColor = Color.FromArgb(255, 255, 255);
                                Take_Chanel.BorderStyle = BorderStyle.None;
                                Take_Chanel.Dock = DockStyle.Top;
                                Take_Chanel.BorderStyle = System.Windows.Forms.BorderStyle.None;
                                Take_Chanel.Cursor = Cursors.Hand;
                                Take_Chanel.Tag = ":Take:" + t + ":User:" + i;

                                //鼠标事件
                                Take_Chanel.Click += new EventHandler(Take_Chanel_Click);
                                Pic_info.Click += new EventHandler(Pic_info_Click);
                                Name_Info.Click += new EventHandler(Label_Info_Click);
                                Take_Chanel.MouseWheel += new MouseEventHandler(OnMouseWheel);

                                Chanel2_Info.Controls.Add(Take_Chanel);

                            }
                        }
                    }

                }

                Chanel2_Info.AutoSize = true;

                //计算容器和滑轮高度，以及判断滑轮是否可用
                Calc_Scroll();
                cCalc_Scroll();
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-Add_Palte:", ex.Message);
                 
            }
        }

        #endregion

        #region 点击好友事件
        /// <summary>
        /// 展开或折叠好友列表，已取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Chanel_panel2_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                Chanel2_Info.Height = 0;
                SetDafault();
                //群聊
                Chanel_panel2.BackColor = Color.FromArgb(245, 245, 245);
                for (int i = 0; i < Chanel_panel2.Controls.Count; i++)
                {
                    Chanel_panel2.Controls[i].BackColor = Color.FromArgb(245, 245, 245);
                }
                //折叠展开
                InitFriendsList();
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-Chanel_panel2_MouseClick:", ex.Message);
            }
           
        }

      /// <summary>
      /// 列表点击事件
      /// </summary>
      /// <param name="sender"></param>
      /// <param name="e"></param>
        private void Take_Chanel_Click(object sender, EventArgs e)
        {
            try
            {
                Panel panel = (Panel)sender;
                TakeObjWrite(panel.Tag.ToString());
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-Take_Chanel_Click:", ex.Message);
            }

        }
        /// <summary>
        /// 列表头像点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Pic_info_Click(object sender, EventArgs e)
        {
            try
            {
                PictureBox Pic = (PictureBox)sender;
                TakeObjWrite(Pic.Tag.ToString());
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-Pic_info_Click:", ex.Message);
            }

        }
        /// <summary>
        ///列表标签点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Label_Info_Click(object sender, EventArgs e)
        {
            try
            {
                Label label = (Label)sender;
                TakeObjWrite(label.Tag.ToString());
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-Label_Info_Click:", ex.Message);
            }

        }
        /// <summary>
        /// 列表点击事件的方法体
        /// </summary>
        /// <param name="Objtag"></param>
        private void TakeObjWrite(string Objtag)
        {
            try
            {
                //避免点击频繁，造成程序崩溃测试
                //if (clickTime.AddSeconds(1.5) > DateTime.Now)
                //{
                //    return;
                //}
                ////重新赋值点击的时间值
                //clickTime = DateTime.Now;

                //进入聊天设置标签可见性
                lb_up.Visible = true;
                lb_down.Visible = false;
                //次数重置
                up_count = 1;
                down_count = 0;

                string str = Objtag;
                string[] sArray = str.Split(new char[2] { ':', ':' });//根据tag拆分，获取到数组下标值

                //群聊
                if (sArray[0] == "Group")
                {
                    currentChatUser = groupPalte[int.Parse(sArray[2]), int.Parse(sArray[4]), 0].ToString();
                    //LogHelper.Log("群号码:", currentChatUser);

                    if (dicGroup.ContainsKey(currentChatUser))
                    {
                        Takepalt_label.Text = dicGroup[currentChatUser].Name.ToString();
                    }
                    else
                    {
                        Takepalt_label.Text = currentChatUser;
                    }

                    //确定当前频道，通讯时当消息标志使用
                    Chanel = int.Parse(sArray[4]);

                    int temp = 0;
                    //切换会话
                    if (OldChanel != Chanel || Chanel == 0)//好友列表的下标的序号值
                    {
                        temp = OldChanel;
                        if (OldChanel != -1 && !htGroup.ContainsKey(temp))
                        {
                            //设置之前选中的OldChanel背景色为默认White，
                            //SetBgColorDefault(dicGroup.Count - 1 - temp);
                            Thread threadSetDefaultBgColor = new Thread(new ParameterizedThreadStart(SetBgColorDefault));
                            threadSetDefaultBgColor.Start((dicGroup.Count - 1 - temp));
                            //定位到聊天底部
                            // SetBgColorDefault(dicGroup.Count - 1 - temp);
                        }

                        //当前聊天界面
                        this.Showinfo_panel.Controls.Clear();
                        //把当前频道赋值给前一个频道
                        OldChanel = Chanel;
                        this.Showinfo_panel.Size = new Size(557, 46);//设置聊天界面大小
                         //设置选中的颜色
                        //SetBgColorSelect(dicGroup.Count - 1 - Chanel);
                        Thread threadSetSelectBgColor = new Thread(new ParameterizedThreadStart(SetBgColorSelect));
                        threadSetSelectBgColor.Start((dicGroup.Count - 1 - Chanel));
                       
                        if (htGroup.ContainsKey(Chanel))
                        {
                            htGroup.Remove(Chanel);
                        }

                        //打开新对话，则重置滑轮高度初始高度
                        climt = -TakeScrollHard_panel.Height;
                        getChatRecord(currentChatUser);//处理数据

                        //TakeScrollHard_panel.Location = new Point(cset_x, climt); //先将位置设置到最下面，定位到最新聊天记录
                    }
                    else
                    {
                        if (temp == -1)//初始时
                        {
                            //设置选中好友的背景色
                            //SetBgColorSelect(dicGroup.Count - 1 - Chanel);
                            Thread threadSetSelectBgColor = new Thread(new ParameterizedThreadStart(SetBgColorSelect));
                            threadSetSelectBgColor.Start((dicGroup.Count - 1 - Chanel));
                            if (htGroup.ContainsKey(Chanel))
                            {
                                htGroup.Remove(Chanel);
                            }
                        }

                        //判断是否显示翻页按钮
                        if (total_count < 10)
                        {
                            this.lb_up.Visible = false;
                        }

                    }
                }
                else
                {
                    //当前用户
                    //currentChatUser = Takepalt_label.Text.ToString().Substring(6).Trim(); //去除"当前会话："文字
                    currentChatUser = palte[int.Parse(sArray[2]), int.Parse(sArray[4]), 0].ToString();
                    //LogHelper.Log("好友号码:", currentChatUser);

                    if (!string.IsNullOrEmpty(dicFriendNames[currentChatUser].ToString()))
                    {
                        Takepalt_label.Text = dicFriendNames[currentChatUser].ToString();
                    }
                    else
                    {
                        Takepalt_label.Text = currentChatUser;
                    }

                    //确定当前频道，通讯时当消息标志使用
                    Chanel = int.Parse(sArray[4]);

                    int temp = 0;
                    //切换会话
                    if (OldChanel != Chanel || Chanel == 0)//好友列表的下标的序号值
                    {
                        temp = OldChanel;
                        if (OldChanel != -1 && !ht.ContainsKey(temp))
                        {
                            //设置之前选中的OldChanel背景色为默认White，
                            //SetBgColorDefault(dic.Count - 1 - temp);
                            Thread threadSetDefaultBgColor = new Thread(new ParameterizedThreadStart(SetBgColorDefault));
                            threadSetDefaultBgColor.Start((dic.Count - 1 - temp));
                        }

                        //当前聊天界面
                        this.Showinfo_panel.Controls.Clear();
                        //把当前频道赋值给前一个频道
                        OldChanel = Chanel;
                        this.Showinfo_panel.Size = new Size(557, 46);//设置聊天界面大小
                         //设置选中的颜色
                        //SetBgColorSelect(dic.Count - 1 - Chanel);
                         Thread threadSetSelectBgColor = new Thread(new ParameterizedThreadStart(SetBgColorSelect));
                         threadSetSelectBgColor.Start((dic.Count - 1 - Chanel));
                        if (ht.ContainsKey(Chanel))
                        {
                            ht.Remove(Chanel);
                        }


                        //打开新对话，则重置滑轮高度初始高度
                        climt = -TakeScrollHard_panel.Height;
                        getChatRecord(currentChatUser);//处理数据

                        //TakeScrollHard_panel.Location = new Point(cset_x, climt); //先将位置设置到最下面，定位到最新聊天记录
                    }
                    else
                    {
                        if (temp == -1)//初始时
                        {
                            //设置选中好友的背景色
                            //SetBgColorSelect(dic.Count - 1 - Chanel);
                            Thread threadSetSelectBgColor = new Thread(new ParameterizedThreadStart(SetBgColorSelect));
                            threadSetSelectBgColor.Start((dic.Count - 1 - Chanel));
                            if (ht.ContainsKey(Chanel))
                            {
                                ht.Remove(Chanel);
                            }
                        }

                        //判断是否显示翻页按钮
                        if (total_count < 10)
                        {
                            this.lb_up.Visible = false;
                        }

                    }
                }

                //移除当前未读
                if (dicUnread.ContainsKey(currentChatUser))
                {
                    dicUnread.Remove(currentChatUser);
                }

            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-TakeObjWrite:", ex.Message);
            }
        }

        #endregion


        #region 群聊       
        /// <summary>
        /// 处理群聊列表信息
        /// </summary>
        public void Get_GroupPlateList()
        {
            #region 群聊列表内容
            try
            {
                //好友按照ID递增排序
                //friend_list.Sort((x, y) => x.CompareTo(y));  -----字典不排序
                //根据好友个数初始化三维数组,并确定大小
                groupPalte = new string[1, dicGroupIds.Count, 4];
                for (int i = 0; i < dicGroupIds.Count; i++)
                {
                    //添加好友列表信息
                    groupPalte[0, i, 0] = dicGroupIds[i];//群聊ID
                    groupPalte[0, i, 1] = "";//描述
                    groupPalte[0, i, 2] = @"Resources\BBGJ.png";//暂时统一设置一张图片
                    groupPalte[0, i, 3] = (dicGroup[dicGroupIds[i]]).Name;//群聊名称
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-Get_PlateList:", ex.Message);        
            }


            #endregion
        }

        /// <summary>
        /// 添加群聊信息Chanel2_Info
        /// </summary>
        private void Add_GroupPalte()
        {
            try
            {
                Get_GroupPlateList();
                for (int t = 0; t > -1; t--)
                {
                    if (dicGroupIds.Count > 0)
                    {
                        for (int i = dicGroupIds.Count - 1; i > -1; i--)
                        {
                            if (groupPalte[t, i, 0] != "" && groupPalte[t, i, 2] != "")  //群id和头像地址
                            {
                                Panel Take_Chanel = new Panel();
                                //设置Take_Chanel的下边界和颜色，方便分割
                                PictureBox Pic_info = new PictureBox();
                                Label Name_Info = new Label();
                                Label Message_Flag = new Label();

                                Pic_info.Size = new Size(40, 40);
                                Pic_info.Image = Image.FromFile(groupPalte[t, i, 2]);
                                Image image = Pic_info.Image;
                                //取消椭圆头像
                                //Image newImage = CutEllipse(image, new Rectangle(0, 0, 100, 100), new Size(40, 40));
                                Pic_info.Image = image;
                                Pic_info.Location = new Point(0, 0);
                                Pic_info.Cursor = Cursors.Hand;
                                Pic_info.Tag = "Group:Take:" + t + ":User:" + i;
                                Take_Chanel.Controls.Add(Pic_info);

                                Name_Info.Size = new Size(85, 25);
                                Name_Info.Font = new Font("微软雅黑", 9);
                                Name_Info.ForeColor = Color.SteelBlue;
                                Name_Info.Text = groupPalte[t, i, 3];//群名

                                Name_Info.Location = new Point(65, 15);//昵称坐标位置
                                Name_Info.Tag = "Group:Take:" + t + ":User:" + i;
                                Take_Chanel.Controls.Add(Name_Info);

                                //消息红点
                                Message_Flag.Size = new Size(25, 25);
                                Message_Flag.Font = new Font("微软雅黑", 14);
                                Message_Flag.Text = "";//圆点
                                //Message_Flag.Text = "●";//圆点

                                Message_Flag.Location = new Point(150, 12);
                                Message_Flag.TextAlign = ContentAlignment.MiddleCenter;
                                Message_Flag.Tag = "Message_Flag";
                                Take_Chanel.Controls.Add(Message_Flag);


                                Take_Chanel.Height = 40;
                                Take_Chanel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 0);
                                Take_Chanel.BackColor = Color.FromArgb(255, 255, 255);
                                Take_Chanel.BorderStyle = BorderStyle.None;
                                Take_Chanel.Dock = DockStyle.Top;
                                Take_Chanel.BorderStyle = System.Windows.Forms.BorderStyle.None;
                                Take_Chanel.Cursor = Cursors.Hand;
                                Take_Chanel.Tag = "Group:Take:" + t + ":User:" + i;

                                //鼠标事件
                                Take_Chanel.Click += new EventHandler(Take_Chanel_Click);
                                Pic_info.Click += new EventHandler(Pic_info_Click);
                                Name_Info.Click += new EventHandler(Label_Info_Click);
                                //Message_Flag.Click += new EventHandler(Label_Info_Click);
                                Take_Chanel.MouseWheel += new MouseEventHandler(OnMouseWheel);

                                Chanel2_Info.Controls.Add(Take_Chanel);

                            }
                        }
                    }

                }

                Chanel2_Info.AutoSize = true;

                //计算容器和滑轮高度，以及判断滑轮是否可用
                Calc_Scroll();
                cCalc_Scroll();
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-Add_GroupPalte:", ex.Message);
                 
            }
        }
        /// <summary>
        /// 从服务器端获取群聊列表
        /// </summary>
        private void GetGroupList()
        {

            try
            {
                SDKClient.Instance.GroupManager.FetchJoinedGroupsFromServer(0, 20, new ValueCallBack<List<AgoraChat.Group>>(
             onSuccess: (groupList) =>
             {
                 groupList = groupList.OrderBy(s=>s.Name).ToList();
                 //群聊列表
                 AddGroup2List(groupList);

                 //本地缓存群成员信息
                 saveGroupMemberInfo();

             }, onError: (code, desc) =>
             {
                 LogHelper.Log("IM获取用户群聊信息失败:", code + ":" + desc);
             }));
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-GetGroupList:", ex.Message);
            }
        }
        /// <summary>
        ///缓存群成员信息到本地
        /// </summary>
        private void saveGroupMemberInfo()
        {
            foreach (var item in dicGroup)
            {
                var groupId = item.Key;
                var groupOwner = item.Value.Owner;
                getGroupMembers(groupId, groupOwner);
            }
        }

        /// <summary>
        /// 群组添加到好友列表
        /// </summary>
        private void AddGroup2List(List<AgoraChat.Group> groups)
        {
            dicGroup.Clear();
            dicGroupIds.Clear();
            for (int i = 0; i < groups.Count; i++)
            {
                dicGroup.Add(groups[i].GroupId, groups[i]);
                dicGroupIds.Add(i, groups[i].GroupId);
            }      
        }
       
      
        /// <summary>
        /// 初始化列表
        /// </summary>
        private void InitGroupList()
        {
           
            //清空好友列表
            Chanel2_Info.Controls.Clear();
            //装内容的panel滚动显示初始位置 
            Chanel2_Info.Top = Top_panel.Height + Chanel_panel2.Height + Chanel_panel4.Height - 90; 
            //重新添加好友列表
            Add_GroupPalte();
            Chanel2_Info.Visible = true;
            Calc_Scroll();

            //设置滚动条
            //limt = ScrollBar_panel.Height - ScrollHard_panel.Height - Top_panel.Height - Chanel_panel2.Height - Chanel_panel4.Height; //滚动最大高度
            //根据消息初始化好友列表颜色

            initGroupListBgColor();

            //勾选第一个
            //if (Chanel2_Info.Controls.Count > 0)
            //{
            //    Take_Chanel_Click((Panel)Chanel2_Info.Controls[dicGroupIds.Count - 1], new EventArgs());
            //    Thread.Sleep(200);
            //}

        }

        #region 群聊点击事件
        /// <summary>
        /// 群聊列表加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Chanel_panel4_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                Chanel2_Info.Height = 0;
                SetDafault();
                //群聊
                Chanel_panel4.BackColor = Color.FromArgb(245, 245, 245);
                for (int i = 0; i < Chanel_panel4.Controls.Count; i++)
                {
                    Chanel_panel4.Controls[i].BackColor = Color.FromArgb(245, 245, 245);
                }
                InitGroupList();
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-Chanel_panel4_MouseClick:", ex.Message);
            }      
        }

        #endregion

        #endregion



        #region 好友列表鼠标事件
        /// <summary>
        /// 列表和群聊列表设置默认背景
        /// </summary>
        private  void SetDafault()
        {
            try
            {
                //好友
                Chanel_panel2.BackColor = Color.FromArgb(255, 255, 255);
                for (int i = 0; i < Chanel_panel2.Controls.Count; i++)
                {
                    Chanel_panel2.Controls[i].BackColor = Color.FromArgb(255, 255, 255);
                }
                //群聊
                Chanel_panel4.BackColor = Color.FromArgb(255, 255, 255);
                for (int i = 0; i < Chanel_panel4.Controls.Count; i++)
                {
                    Chanel_panel4.Controls[i].BackColor = Color.FromArgb(255, 255, 255);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-SetDafault:", ex.Message);
            } 
        }
       
        #endregion

        #region 界面颜色方法
        /// <summary>
        /// 设置好友消息列表颜色
        /// </summary>
        public void initFriendsListBgColor()
        {
            try
            {
                foreach (var item in dic)
                {
                    if (ht.ContainsKey(item.Key))
                    {
                        //设置当前行背景色
                        Thread threadSetBgColor = new Thread(new ParameterizedThreadStart(SetBgColor));
                        threadSetBgColor.Start((dic.Count - 1 - item.Key));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log("initFriendsListBgColor:", ex.Message);
            }
           
        }

        /// <summary>
        /// 设置群组列表颜色
        /// </summary>
        public void initGroupListBgColor()
        {
            try
            {
                foreach (var item in dicGroupIds)
                {
                    if (htGroup.ContainsKey(item.Key))
                    {
                        //设置当前行背景色
                        Thread threadSetBgColor = new Thread(new ParameterizedThreadStart(SetBgColor));
                        threadSetBgColor.Start((dicGroupIds.Count - 1 - item.Key));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log("initGroupListBgColor:", ex.Message);
            }
            
        }

        /// <summary>
        /// 设置好友列表背景色
        /// </summary>
        /// <param name="o"></param>
        public void SetBgColor(object o)
        {
            try
            {
                int i = (int)o;
                //设置好友列表背景色
                //Chanel2_Info.Controls[i].BackColor = Color.LightSkyBlue;
                //Chanel2_Info.Controls[i].Controls[0].BackColor = Color.LightSkyBlue;
                //Chanel2_Info.Controls[i].Controls[1].BackColor = Color.LightSkyBlue;

                Chanel2_Info.Controls[i].Controls[2].ForeColor = Color.Red;
                Chanel2_Info.Controls[i].Controls[2].Text = "●";
           
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-SetBgColor:", ex.Message);
            }

        }

        /// <summary>
        /// 好友列表恢复默认背景色
        /// </summary>
        /// <param name="o"></param>
        public void SetBgColorDefault(object o)
        {
            try
            {
                int i = (int)o;
                if (i >= 0)
                {
                    //设置好友列表背景色
                    Chanel2_Info.Controls[i].BackColor = Color.White;
                    Chanel2_Info.Controls[i].Controls[0].BackColor = Color.White;
                    Chanel2_Info.Controls[i].Controls[1].BackColor = Color.White;
                    Chanel2_Info.Controls[i].Controls[2].ForeColor = Color.White;
                    Chanel2_Info.Controls[i].Controls[2].Text = "";
                    //Application.DoEvents();
                }

            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-SetBgColorDefault:", ex.Message);
            }

        }

        /// <summary>
        /// 设置选中颜色
        /// </summary>
        /// <param name="o"></param>
        public void SetBgColorSelect(object o)
        {
            try
            {
                int i = (int)o;
                if (i >= 0)
                {
                    //设置好友列表背景色
                    Chanel2_Info.Controls[i].BackColor = Color.Gainsboro;
                    Chanel2_Info.Controls[i].Controls[0].BackColor = Color.Gainsboro;
                    Chanel2_Info.Controls[i].Controls[1].BackColor = Color.Gainsboro;
                    Chanel2_Info.Controls[i].Controls[2].Text = "";
                    Chanel2_Info.Controls[i].Controls[2].ForeColor = Color.Gainsboro;
                    //Application.DoEvents();
                }

            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-SetBgColorSelect:", ex.Message);
            }

        }

        #endregion

        #region Function

        #region 获取聊天记录
        /// <summary>
        /// 根据好友获取聊天记录
        /// </summary>
        /// <param name="u"></param>
        public void getChatRecord(string user)
        {
            try
            {
                Conversation conversation = SDKClient.Instance.ChatManager.GetConversation(user);
                conversation.LoadMessages(null, 200, MessageSearchDirection.UP, new ValueCallBack<List<AgoraChat.Message>>(
                    onSuccess: (messages) =>
                    {
                        try
                        {
                            Totallist = messages.OrderBy(s => s.ServerTime).ToList();
                            total_count = Totallist.Count;

                            if (total_count > 10)//大于10条，取前10条
                            {
                                lb_up.Visible = true;
                                for (int i = total_count - 10; i < total_count; i++)
                                {
                                    //获取一个消息
                                    AgoraChat.Message message = Totallist[i];
                                    //获取消息的时间
                                    string timeTick = message.ServerTime.ToString();
                                    //定义字符串数组
                                    MsgBody msgBody = new MsgBody();
                                    //公共字段
                                    msgBody.direction = message.Direction.ToString();
                                    msgBody.currentChat = currentChatUser;
                                    msgBody.chanelId = Chanel.ToString();
                                    msgBody.loginUser = UserName;
                                    //计算消息时间
                                    msgBody.serverTime = ChatUtility.getTimeByMillsSpan(timeTick);
                                    msgBody.messageFrom = message.From;
                                    //先转文本
                                    var body = message.Body as AgoraChat.MessageBody.TextBody;

                                    //判断分为文字和图片
                                    if (body != null)//文本
                                    {
                                        string sendMsg = body.Text;
                                        if (string.IsNullOrEmpty(sendMsg))//空文本不显示跳过
                                        {
                                            continue;
                                        }
                                        if (sendMsg.Length > 300)//长文本不显示，测试
                                        {
                                            continue;
                                        }
                                        msgBody.urlPath = "";
                                        msgBody.rtfStr = ChatUtility.str2Rtf(sendMsg);
                                        msgBody.otherDesc = "";
                                    }
                                    else//图片 、音频
                                    {
                                        var ImagesBody = message.Body as AgoraChat.MessageBody.ImageBody;
                                        if (ImagesBody != null)
                                        {
                                            string imagesPath = ImagesBody.RemotePath;
                                            if (string.IsNullOrEmpty(imagesPath))//路径为空，则跳过
                                            {
                                                continue;
                                            }
                                            msgBody.urlPath = imagesPath;
                                            msgBody.rtfStr = "";
                                            msgBody.otherDesc = "图片";
                                        }
                                        else
                                        {
                                            var VoiceBody = message.Body as AgoraChat.MessageBody.VoiceBody;
                                            if (VoiceBody != null)
                                            {
                                                string voicePath = VoiceBody.RemotePath;
                                                if (string.IsNullOrEmpty(voicePath))//路径为空，则跳过
                                                {
                                                    continue;
                                                }
                                                //语音
                                                msgBody.urlPath = voicePath;
                                                msgBody.rtfStr = ChatUtility.str2Rtf("语音:)))");
                                                msgBody.otherDesc = "语音";
                                            }
                                            else
                                            {
                                                continue;
                                            }

                                        }
                                    }

                                    //定位到聊天底部
                                    this.Invoke(new InvokeHandler(delegate ()
                                    {
                                        HandleRecordMessage(msgBody);
                                    }));

                                }
                            }
                            else//小于10条，取全部
                            {
                                lb_up.Visible = false;
                                for (int i = 0; i < total_count; i++)
                                {
                                    //获取一个消息
                                    AgoraChat.Message message = Totallist[i];
                                    //获取消息的时间
                                    string timeTick = message.ServerTime.ToString();
                                    //定义字符串数组
                                    MsgBody msgBody = new MsgBody();
                                    //公共字段
                                    msgBody.direction = message.Direction.ToString();//SEND  && RECEIVE
                                    msgBody.currentChat = currentChatUser;
                                    msgBody.chanelId = Chanel.ToString();//index
                                    msgBody.loginUser = UserName;
                                    //计算消息时间
                                    msgBody.serverTime = ChatUtility.getTimeByMillsSpan(timeTick);
                                    msgBody.messageFrom = message.From;

                                    //先转文本
                                    var body = message.Body as AgoraChat.MessageBody.TextBody;

                                    //判断分为文字和图片
                                    if (body != null)//文本
                                    {
                                        string sendMsg = body.Text;
                                        if (string.IsNullOrEmpty(sendMsg))//空文本不显示跳过
                                        {
                                            continue;
                                        }

                                        msgBody.urlPath = "";
                                        msgBody.rtfStr = ChatUtility.str2Rtf(sendMsg);
                                        msgBody.otherDesc = "";
                                    }
                                    else//图片、语音
                                    {
                                        var ImagesBody = message.Body as AgoraChat.MessageBody.ImageBody;
                                        if (ImagesBody != null)
                                        {
                                            string imagesPath = ImagesBody.RemotePath;
                                            if (string.IsNullOrEmpty(imagesPath))//路径为空，则跳过
                                            {
                                                continue;
                                            }
                                            msgBody.urlPath = imagesPath;
                                            msgBody.rtfStr = "";
                                            msgBody.otherDesc = "图片";
                                        }
                                        else
                                        {
                                            var VoiceBody = message.Body as AgoraChat.MessageBody.VoiceBody;
                                            if (VoiceBody != null)
                                            {
                                                string voicePath = VoiceBody.RemotePath;
                                                if (string.IsNullOrEmpty(voicePath))//路径为空，则跳过
                                                {
                                                    continue;
                                                }

                                                msgBody.urlPath = voicePath;
                                                msgBody.rtfStr = ChatUtility.str2Rtf("语音:)))");
                                                msgBody.otherDesc = "语音";
                                            }
                                            else
                                            {
                                                continue;
                                            }

                                        }
                                    }

                                    //聊天记录更新
                                    this.Invoke(new InvokeHandler(delegate ()
                                    {
                                        HandleRecordMessage(msgBody);
                                    }));

                                }
                            }

                            //定位到聊天底部
                            //this.Invoke(new InvokeHandler(delegate ()
                            //{
                            //    NavigateToBottom();
                            //}));
                            this.Invoke((Action)delegate
                            {
                                NavigateToBottom();
                            });
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Log("IM获取聊天记录失败:",ex.Message);
                        }
                    },
                    onError: (code, desc) =>
                    {
                        LogHelper.Log("IM获取聊天记录失败:", code + ":" + desc);
                    }
                ));
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-getChatRecord:", ex.Message);
            }
        }
        #endregion


        #region 弹窗
        /// <summary>
        /// 右下角消息弹窗委托方法
        /// </summary>
        /// <param name="t"></param>
        /// <param name="c"></param>
        public void UpdateTxtMethod(string t, string c)
        {
            ShowTip(t, c);
        }

        FrmAlertCustom msg = new FrmAlertCustom("", "");
        /// <summary>
        /// 消息提示方法体
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        public void ShowTip(string title, string content)
        {
            string showTipTitle = title;
            content = !string.IsNullOrEmpty(content) ? content : "图片消息";
            if (title.Length >= 15)
            {
                showTipTitle = dicGroup[title].Name;//群名
            }
            else
            {
                showTipTitle = dicFriendNames[title] == "" ? title : dicFriendNames[title];//工号或者姓名
            }
            //弹窗提示
            msg = new FrmAlertCustom(showTipTitle, string.Format("消息内容：{0}，时间：{1}", content, DateTime.Now.ToString("HH:mm:ss")));
            msg.ClickView += (sender1, e1) =>
            {
                if (this.WindowState == FormWindowState.Minimized)
                {
                    this.WindowState = FormWindowState.Normal;
                }
                this.StartPosition = FormStartPosition.CenterScreen;
                this.Activate();
                this.Show();

                //选中打开好友对话框
                NavigateRecord(title, content);
            };

            try
            {
                msg.ShowAlert();
            }
            catch (Exception ex)
            {
                msg.Close();
            }

        }

        /// <summary>
        /// 打开弹窗框定位聊天记录
        /// </summary>
        /// <param name="user"></param>
        /// <param name="content"></param>
        public void NavigateRecord(string user, string content)
        {
            try
            {
                int index = 0;
                if (user.Length >= 15)
                {
                    index = dicGroupIds.FirstOrDefault(s => s.Value == user).Key;//群聊
                }
                else
                {
                    index = dic.FirstOrDefault(s => s.Value == user).Key;//好友
                }

                //查找到对应的下标值，直接追加消息
                //int index = dic.FirstOrDefault(s => s.Value == user).Key;
                if (OldChanel == index && IsOpenChatFrm())//直接追加消息
                {

                  MsgBody msgBody = new MsgBody();
                    msgBody.direction = "RECEIVE";//SEND  &&  RECEIVE
                    msgBody.currentChat = user;//聊天对象
                    msgBody.urlPath = "";
                    msgBody.chanelId = index.ToString();//当前好友index
                    msgBody.rtfStr = ChatUtility.str2Rtf(content);
                    msgBody.loginUser = UserName;//当前用户
                    msgBody.serverTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    msgBody.otherDesc = "";
                    msgBody.messageFrom = user;//聊天对象

                    if (content == "图片消息")
                    {
                        //图片
                        msgBody.urlPath = "";//通过全局变量传地址
                        msgBody.rtfStr = receiveImagePath;//文本值
                        msgBody.otherDesc = "图片";

                        ////当仅仅为一个好友时，防止好友列表下标越界
                        //int t = dic.Count - index - 1 >= 0 ? dic.Count - index - 1 : 0;
                        ////重新打开信好友列表==>拿不到图片地址，采用刷新从服务端重新获取
                        //RefeshReciveImage((Panel)Chanel2_Info.Controls[t]);
                        //return;
                    }
                    else if (content == "语音消息")
                    {
                        //语音消息
                        msgBody.urlPath = receiveVoicePath;
                        msgBody.rtfStr = ChatUtility.str2Rtf("语音:)))");
                        msgBody.otherDesc = "语音";
                    }
                    else
                    {
                        //文本
                        msgBody.urlPath = "";
                        msgBody.rtfStr = ChatUtility.str2Rtf(content);
                        msgBody.otherDesc = "";
                    }


                    if (user.Length >= 15)
                    {
                        //判断是否已经追加过聊天记录
                        if (htGroup.ContainsKey(index))
                        {
                            //追加消息               
                            this.Invoke(new InvokeHandler(delegate ()
                            {
                                HandleMessage(msgBody);
                            }));

                            htGroup.Remove(index);
                        }
                    }
                    else
                    {
                        //判断是否已经追加过聊天记录
                        if (ht.ContainsKey(index))
                        {
                            //追加消息               
                            this.Invoke(new InvokeHandler(delegate ()
                            {
                                HandleMessage(msgBody);
                            }));

                            ht.Remove(index);
                        }
                    }

                    

                }
                else
                {
                    //当仅仅为一个好友时，防止好友列表下标越界
                    int t = 0;
                    if (user.Length >= 15)
                    {
                        //打开群聊
                         Chanel_panel4_MouseClick(null, null);
                        //当仅仅为一个好友时，防止好友列表下标越界
                        t = dicGroupIds.Count - index - 1 >= 0 ? dicGroupIds.Count - index - 1 : 0;
                    }
                    else
                    {
                        //打开好友
                         Chanel_panel2_MouseClick(null, null);
                        //当仅仅为一个好友时，防止好友列表下标越界
                        t = dic.Count - index - 1 >= 0 ? dic.Count - index - 1 : 0;
                    }
                    //当仅仅为一个好友时，防止好友列表下标越界
                    //int t = dic.Count - index - 1 >= 0 ? dic.Count - index - 1 : 0;

                    //打开信好友列表
                    //Thread.Sleep(100);
                    Take_Chanel_Click((Panel)Chanel2_Info.Controls[t], new EventArgs());
                }

                //移除当前未读
                if (dicUnread.ContainsKey(user))
                {
                    dicUnread.Remove(user);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-NavigateRecord:", ex.Message);         
            }

        }
        #endregion

        #region 上翻页

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lb_up_Click(object sender, EventArgs e)
        {
            try
            {
                if (up_count < 1)
                {
                    MessageBox.Show("没有更多历史聊天消息！");
                    lb_up.Visible = false;
                    return;
                }
                else
                {
                    if (up_count <= 19)
                    {
                        up_count++;
                        getUpRecord();
                        if (lb_up.Visible == true)
                        {
                            lb_down.Visible = true;
                            //lb_down.Enabled = true;
                            down_count--;
                        }

                    }
                    else
                    {
                        MessageBox.Show("没有更多历史聊天消息！");
                        lb_up.Visible = false;
                        return;
                    }
                }
                //down_count--;
            }
            catch (Exception ex)
            {
                LogHelper.Log("lb_up_Click:", ex.Message);
            }
           
        }

        /// <summary>
        /// 获取上翻页聊天记录
        /// </summary>
        public void getUpRecord()
        {
            try
            {
                bool IsClear = true;
                //判断起始值
                int t = (total_count - (up_count * 10)) < 0 ? 0 : (total_count - (up_count * 10));
                //无聊天记录则退出
                if (total_count <= 10)
                {
                    lb_up.Visible = false;
                    lb_down.Visible = false;
                    up_count--;
                    MessageBox.Show("没有更多历史聊天消息！");
                    return;
                }
                else if (t >= total_count - ((up_count - 1) * 10))
                {
                    lb_up.Visible = false;
                    lb_down.Visible = true;
                    up_count--;
                    MessageBox.Show("没有更多历史聊天消息！");
                    return;
                }

                for (int i = t; i < total_count - ((up_count - 1) * 10); i++)
                {
                    //获取一个消息
                    AgoraChat.Message message = Totallist[i];
                    //获取消息的时间
                    string timeTick = message.ServerTime.ToString();
                    //定义字符串数组
                  MsgBody msgBody = new MsgBody();

                    //公共字段
                    msgBody.direction = message.Direction.ToString();//SEND  && RECEIVE
                    msgBody.currentChat = currentChatUser;
                    msgBody.chanelId = Chanel.ToString();//index
                    msgBody.loginUser = UserName;//用户
                    msgBody.serverTime = ChatUtility.getTimeByMillsSpan(timeTick);
                    msgBody.messageFrom = message.From;

                    //先转文本
                    var body = message.Body as AgoraChat.MessageBody.TextBody;

                    //判断分为文字和图片
                    if (body != null)//文本
                    {
                        string sendMsg = body.Text;
                        if (string.IsNullOrEmpty(sendMsg))//空文本不显示跳过
                        {
                            continue;
                        }
                        if (sendMsg.Length > 300)//长文本则不显示
                        {
                            continue;
                        }
                        //文本字段
                        msgBody.urlPath = "";
                        msgBody.rtfStr = ChatUtility.str2Rtf(sendMsg);
                        msgBody.otherDesc = "";
                    }
                    else//图片、语音
                    {
                        var ImagesBody = message.Body as AgoraChat.MessageBody.ImageBody;
                        if (ImagesBody != null)
                        {
                            string imagesPath = ImagesBody.RemotePath;
                            if (string.IsNullOrEmpty(imagesPath))//路径为空，则跳过
                            {
                                continue;
                            }
                            msgBody.urlPath = imagesPath;
                            msgBody.rtfStr = "";//图片不需要rtf值
                            msgBody.otherDesc = "图片";
                        }
                        else
                        {
                            var VoiceBody = message.Body as AgoraChat.MessageBody.VoiceBody;
                            if (VoiceBody != null)
                            {
                                string voicePath = VoiceBody.RemotePath;
                                if (string.IsNullOrEmpty(voicePath))//路径为空，则跳过
                                {
                                    continue;
                                }
                                //语音
                                msgBody.urlPath = voicePath;
                                msgBody.rtfStr = ChatUtility.str2Rtf("语音:)))");
                                msgBody.otherDesc = "语音";
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }

                    //第一次向界面添加信息前，清空之前
                    if (IsClear)
                    {
                        //当前聊天界面
                        this.Showinfo_panel.Controls.Clear();
                        this.Showinfo_panel.Size = new Size(557, 46);//聊天界面大小
                        climt = -TakeScrollHard_panel.Height;

                        //修改值
                        IsClear = false;
                    }

                    //信息添加到界面
                    this.Invoke(new InvokeHandler(delegate ()
                    {
                        HandleRecordMessage(msgBody);
                    }));

                }

                //定位到底部
                this.Invoke((Action)delegate
                {
                    NavigateToBottom();
                });
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-getUpRecord:", ex.Message);
                 
            }
          
        }
      
        #endregion

        #region 下翻页
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lb_down_Click(object sender, EventArgs e)
        {
            try
            {
                if (down_count > -1)
                {
                    lb_down.Visible = false;
                    MessageBox.Show("没有更多最新聊天消息！");
                    lb_up.Visible = true;
                    return;
                }
                else
                {
                    getDownRecord();
                    if (lb_down.Visible == true)
                    {
                        lb_up.Visible = true;
                        down_count++;
                    }
                    up_count--;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log("lb_down_Click:", ex.Message);
            }
           

        }   
        /// <summary>
        /// 获取下翻页聊天记录
        /// </summary>
        public void getDownRecord()
        {
            try
            {
                bool IsClear = true;
                //判断最大值
                int t = total_count + ((down_count + 1) * 10) < total_count + (down_count * 10) ? total_count : total_count + ((down_count + 1) * 10);
                //无聊天记录则退出
                if (total_count <= 10 || total_count + (down_count * 10) >= t)
                {
                    lb_down.Visible = false;
                    down_count--;
                    MessageBox.Show("没有更多最新聊天消息！");
                    lb_up.Visible = true;
                    return;
                }

                for (int i = total_count + (down_count * 10); i < t; i++)
                {
                    //获取一个消息
                    AgoraChat.Message message = Totallist[i];
                    //获取消息的时间
                    string timeTick = message.ServerTime.ToString();
                    //定义字符串数组
                  MsgBody msgBody = new MsgBody();

                    //公共字段
                    msgBody.direction = message.Direction.ToString();//SEND  && RECEIVE
                    msgBody.currentChat = currentChatUser;
                    msgBody.chanelId = Chanel.ToString();//index
                    msgBody.loginUser = UserName;//用户
                    msgBody.serverTime = ChatUtility.getTimeByMillsSpan(timeTick);
                    msgBody.messageFrom = message.From;

                    //先转文本
                    var body = message.Body as AgoraChat.MessageBody.TextBody;

                    //判断分为文字和图片
                    if (body != null)//文本
                    {
                        string sendMsg = body.Text;
                        if (string.IsNullOrEmpty(sendMsg))//空文本不显示跳过
                        {
                            continue;
                        }
                        if (sendMsg.Length > 300)//长文本不显示，测试
                        {
                            continue;
                        }
                        msgBody.urlPath = "";
                        msgBody.rtfStr = ChatUtility.str2Rtf(sendMsg);
                        msgBody.otherDesc = "";
                    }
                    else//图片、音频
                    {
                        var ImagesBody = message.Body as AgoraChat.MessageBody.ImageBody;
                        if (ImagesBody != null)
                        {
                            string imagesPath = ImagesBody.RemotePath;
                            if (string.IsNullOrEmpty(imagesPath))//路径为空，则跳过
                            {
                                continue;
                            }
                            msgBody.urlPath = imagesPath;
                            msgBody.rtfStr = "";
                            msgBody.otherDesc = "图片";
                        }
                        else
                        {
                            var VoiceBody = message.Body as AgoraChat.MessageBody.VoiceBody;
                            if (VoiceBody != null)
                            {
                                string voicePath = VoiceBody.RemotePath;
                                if (string.IsNullOrEmpty(voicePath))//路径为空，则跳过
                                {
                                    continue;
                                }
                                msgBody.urlPath = voicePath;
                                msgBody.rtfStr = ChatUtility.str2Rtf("语音:)))");
                                msgBody.otherDesc = "语音";
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }

                    //第一次向界面添加信息前，清空之前
                    if (IsClear)
                    {
                        //当前聊天界面
                        this.Showinfo_panel.Controls.Clear();
                        this.Showinfo_panel.Size = new Size(557, 46);//聊天界面大小
                        climt = -TakeScrollHard_panel.Height;
                        IsClear = false;
                    }

                    //渲染到界面
                    this.Invoke(new InvokeHandler(delegate ()
                    {
                        HandleRecordMessage(msgBody);
                    }));

                }

                //定位
                this.Invoke((Action)delegate
                {
                    NavigateToBottom();
                });
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-getDownRecord:", ex.Message);
                 
            }
           
        }

        #endregion

        #region 发送
        /// <summary>
        /// 编辑框回车监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Rich_Edit_Enter(object sender, KeyEventArgs e)
        {
            //判断是否有回车键输入
            if (e.KeyCode == Keys.Control || e.KeyCode == Keys.Enter)
            {
                SendEventHandle();
            }
        }

        /// <summary>
        /// 点击发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void send_btn_MouseClick(object sender, MouseEventArgs e)
        {
            SendEventHandle();
        }

       /// <summary>
       /// 发送处理事件
       /// </summary>
        private void SendEventHandle()
        {
            try
            {
                if (Chanel != -1)//当前用户
                {
                    MsgBody msgBody = new MsgBody();
                    string sendMsg = Rich_Edit.Text.ToString();//发送文本

                    //消息类型
                    msgBody.direction = "SEND";
                    //当前聊天用户
                    msgBody.currentChat = currentChatUser;
                    msgBody.urlPath = "";
                    //聊天用户对应ID
                    msgBody.chanelId = Chanel.ToString();
                    //发送的rtf文本
                    msgBody.rtfStr = Rich_Edit.Rtf;
                    //当前用户标识
                    msgBody.loginUser = UserName;
                    msgBody.serverTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    msgBody.otherDesc = "";
                    msgBody.messageFrom = UserName;

                    if (string.IsNullOrEmpty(sendMsg.Trim()))
                    {
                        if (is_sendImg)
                        {
                            msgBody.urlPath = filePath;//图片路径
                            msgBody.rtfStr = "";//用于计算气泡高度,图片不通过rtf计算
                            msgBody.otherDesc = "图片";
                            //图片发送到服务器
                            //群聊Id
                            if (currentChatUser.Length >= 15)
                            {
                                SendImg(currentChatUser, filePath, msgBody, MessageType.Group);
                            }
                            else
                            {
                                SendImg(currentChatUser, filePath, msgBody);
                            }
                        
                            //最后重置
                            is_sendImg = false;
                            Rich_Edit.Clear();
                        }
                        else
                        {
                            MessageBox.Show("请输入发送内容！");
                        }
                    }
                    else
                    {
                        //群聊Id
                        if (currentChatUser.Length>= 15)
                        {
                            SendTxt(currentChatUser, sendMsg, msgBody, MessageType.Group);
                        }
                        else
                        {
                            SendTxt(currentChatUser, sendMsg, msgBody);
                        }
                      
                        Rich_Edit.Clear();
                    }
                }
                else
                {
                    MessageBox.Show("请先从好友列表中先选择一位好友！");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-SendEvent ", ex.Message);
                 
            }

        }

        #region  图片发送
       /// <summary>
       /// 图片发送到服务器
       /// </summary>
       /// <param name="to_user"></param>
       /// <param name="localPath"></param>
       /// <param name="msgBody"></param>
       /// <param name="messageType"></param>
        public void SendImg(string to_user, string localPath,MsgBody msgBody, MessageType messageType = MessageType.Chat)
        {
            try
            {
                AgoraChat.Message msg = AgoraChat.Message.CreateImageSendMessage(to_user, localPath);
                msg.MessageType = messageType;
                SDKClient.Instance.ChatManager.SendMessage(ref msg, new CallBack(
                    onSuccess: () =>
                    {
                        if (up_count != 1)
                        {
                            //当前聊天界面
                            this.Showinfo_panel.Controls.Clear();
                            this.Showinfo_panel.Size = new Size(557, 46);//聊天界面大小

                            //聊天界面高度
                            climt = - TakeScrollHard_panel.Height;

                            //重置上下翻页数
                            up_count = 1;
                            down_count = 0;

                            //下10条标签隐藏
                            lb_down.Visible = false;
                            //重新获取近10条聊天记录
                            getChatRecord(currentChatUser);//处理数据
                        }
                        else//直接追加
                        {
                            //更新内存消息
                            Totallist.Add(msg);
                            total_count = Totallist.Count;
                            //更新界面
                            this.Invoke(new InvokeHandler(delegate ()
                            {
                                HandleMessage(msgBody);
                            }));
                        }
                    },
                    onProgress: (progress) =>
                    {

                    },
                    onError: (code, desc) =>
                    {
                        LogHelper.Log($"IM发送图片失败:", $" code: {code}, desc: {desc}");
                        MessageBox.Show($"IM发送图片失败, code: {code}, desc: {desc}");            
                    }
                ));
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-SendImg:", ex.Message);
            }

        }
        /// <summary>
        /// 点击选择发送图片的图标按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sendImag_btn_MouseClick(object sender, MouseEventArgs e)
        {
            selectFile();
        }
        bool is_sendImg = false;
        string filePath = "";
        /// <summary>
        /// 选择发送的文件
        /// </summary>
        private void selectFile()
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "Files|*.png;*.jpg";              // 设定打开的文件类型
                //openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;                       // 打开app对应的路径
                openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);  // 打开桌面

                // 如果选定了文件
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 取得文件路径及文件名
                    filePath = openFileDialog.FileName;

                    //Rich_Edit 中添加图片
                    Bitmap bmp = new Bitmap(filePath);//获得图片
                    Clipboard.SetDataObject(bmp, false);//将图片放在剪贴板中
                    if (Rich_Edit.CanPaste(DataFormats.GetFormat(DataFormats.Bitmap)))
                        Rich_Edit.Paste();//粘贴数据

                    //设置发照片flag
                    is_sendImg = true;
                }

            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-selectFile:", ex.Message);
                 
            }

        }
        #endregion

        #region 文本发送
        /// <summary>
        /// 好友发送文本
        /// </summary>
        /// <param name="to_user"></param>
        /// <param name="message"></param>
        /// <param name="msgBody"></param>
        /// <param name="messageType"></param>
        public void SendTxt(string to_user, string message, MsgBody msgBody,MessageType messageType = MessageType.Chat)
        {
            try
            {
                //Dictionary<string, AttributeValue> ext = new Dictionary<string, AttributeValue>();
                //AttributeValue v = AttributeValue.Of(to_user, AttributeValueType.STRING);
                //ext.Add("xiaoming", v);
                AgoraChat.Message msg = AgoraChat.Message.CreateTextSendMessage(to_user, message);
                //msg.Attributes = ext;
                msg.MessageType = messageType;

                SDKClient.Instance.ChatManager.SendMessage(ref msg, new CallBack(
                    onSuccess: () =>
                    {
                        if (up_count != 1)
                        {
                            //当前聊天界面
                            this.Showinfo_panel.Controls.Clear();
                            this.Showinfo_panel.Size = new Size(557, 46);//聊天界面大小

                            //重置初始滑动高度
                            climt = -TakeScrollHard_panel.Height;

                            //重置上下翻页数
                            up_count = 1;
                            down_count = 0;

                            //下10条标签隐藏
                            lb_down.Visible = false;

                            //重新获取近10条聊天记录
                            getChatRecord(currentChatUser);//处理数据
                        }
                        else//直接追加
                        {
                            //更新内存消息
                            Totallist.Add(msg);
                            total_count = Totallist.Count;
                            //更新界面
                            this.Invoke(new InvokeHandler(delegate ()
                            {
                                HandleMessage(msgBody);
                            }));
                        }
                    },
                    onError: (code, desc) =>
                    {
                        LogHelper.Log($"IM发送文本失败:", $" code: {code}, desc: {desc}");
                        MessageBox.Show($"IM发送文本失败, code: {code}, desc: {desc}");
                    }
                ));
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-SendTxt:", ex.Message);        
            }

        }

        #endregion

        #endregion

        #region 处理界面聊天记录
        /// <summary>
        /// 处理聊天记录消息
        /// </summary>
        /// <param name="msgBody"></param>
        private void HandleRecordMessage(MsgBody msgBody)
        {
            #region 程序崩溃记录查看log
            //string inputstr = JsonConvert.SerializeObject(msgBody);
            //LogHelper.Log("MsgBody:", inputstr);
            #endregion
            try
            {
                #region 
                ////计算内容所占的宽度
                //if (msgBody.otherDesc  == "图片")// 计算图片的长宽
                //{
                //    Linewidth = 300;
                //    Lineheight = 300;//或者根据图片真实值设定
                //}
                //else//文本
                //{
                //    ChatUtility.Calc_PanelWidth(msgBody.rtfStr,out Linewidth, out Lineheight);
                //}
                #endregion

                //计算内容所占的宽度
                if (msgBody.otherDesc  == "")//文本
                {
                    ChatUtility.Calc_PanelWidth(msgBody.rtfStr,out Linewidth, out Lineheight);
                }
                else if (msgBody.otherDesc  == "图片")// 计算图片的长宽
                {
                    Linewidth = 300;
                    Lineheight = 300;//或者根据图片真实值设定
                }
                else if (msgBody.otherDesc  == "语音")
                {
                    //根据文本值，设置统一的长度和高度
                }

                //是否当前模块
                if (msgBody.chanelId == Chanel.ToString())
                {
                    Panel uTake = new Panel();
                    PictureBox hard_img = new PictureBox();
                    Label u_name = new Label();
                    Panel conter_panel = new Panel();
                    Panel rc = new Panel();
                    //使用改变的PicRichTextBox，为背景透明
                    RichTextBoxEx rich_conter = new RichTextBoxEx();


                    if (msgBody.currentChat.Length >= 15)
                    {
                        //if (msgBody.direction == "SEND")
                        //{
                        //    u_name.Text = msgBody.serverTime + "  " + msgBody.messageFrom; //用户
                        //}
                        //else
                        //{
                        //    u_name.Text = msgBody.messageFrom + "  " + msgBody.serverTime; //用户
                        //}

                        if (msgBody.direction == "SEND")
                        {
                            //u_name.Text = msgBody.serverTime + " (" + msgBody.messageFrom + ") " + (dicGroupMembers[msgBody.currentChat][msgBody.messageFrom]).NickName; //时间 + （用户） + 姓名

                            u_name.Text = msgBody.serverTime + " (" + msgBody.messageFrom + ") 调度员" ; //时间 + （用户） + 姓名
                        }
                        else
                        {
                            //u_name.Text = (dicGroupMembers[msgBody.currentChat][msgBody.messageFrom]).NickName + " (" + msgBody.messageFrom + ") " + msgBody.serverTime; //姓名 +（用户） + 时间

                            u_name.Text = "调度员 (" + msgBody.messageFrom + ") " + msgBody.serverTime; //姓名 +（用户） + 时间
                        }

                    }
                    else
                    {
                        u_name.Text = msgBody.serverTime;//时间
                    }
                    //u_name.AutoSize = true;
                    u_name.Height = 17;
                    u_name.Width = 225;
                    //u_name.ForeColor = Color.FromArgb(195, 195, 195);
                    //u_name.ForeColor = Color.FromArgb(77, 77, 255);
                    u_name.ForeColor = Color.FromArgb(47, 12, 247);//聊天界面用户信息颜色
                   
                    //判断是否本人，本人右侧显示，其他左侧显示
                    //if (msgBody.loginUser == UserName)
                    if (msgBody.direction == "SEND")
                    {
                        hard_img.Size = new Size(64, 64);
                        hard_img.Image = Image.FromFile(@"Resources\BBGJ_Chat.png");
                        Image image = hard_img.Image;
                        //Image newImage = CutEllipse(image, new Rectangle(0, 0, 200, 200), new Size(64, 64));
                        hard_img.Image = image;
                        hard_img.Location = new Point(550, 17);

                        //时间位置
                        //u_name.Location = new Point(470, 0);
                        u_name.Location = new Point(410, 0);
                        u_name.TextAlign = ContentAlignment.MiddleRight;

                        if (msgBody.otherDesc  == "语音")//当为音频时
                        {
                            string voicePath = @"sdkdata\appdata\" + msgBody.loginUser + "\\" + msgBody.currentChat;
                            //语音SDK自动缓存路径为：sdkdata\appdata\8226\000049\音频.mp3
                            //文件路径
                            string url = msgBody.urlPath;
                            if (url == "")
                            {
                                return;
                            }

                            //获取音频文件名
                            string file_name = url.Substring(url.LastIndexOf("/") + 1);
                            if (!file_name.ToLower().Contains(".mp3"))
                            {
                                file_name += ".mp3";
                            }

                            //音频文件路径
                            string voiceFile = voicePath + "\\" + file_name;

                            //不存在则下载
                            if (!File.Exists(voiceFile))
                            {
                                ChatUtility.DownLoadFiles(url, voiceFile);
                            }

                            string mp3Times = ChatUtility.getMp3Times(voiceFile);
                            string content = "语音消息 " + mp3Times + "″" + ")))";
                            rich_conter.Rtf = ChatUtility.str2Rtf(content);
                            ChatUtility.Calc_PanelWidth(msgBody.rtfStr,out Linewidth, out Lineheight);
                            rich_conter.Cursor = Cursors.Hand;

                            rich_conter.WordWrap = true;
                            rich_conter.ReadOnly = true;
                            rich_conter.BorderStyle = BorderStyle.None;
                            rich_conter.ScrollBars = RichTextBoxScrollBars.None;
                            rich_conter.Location = new Point(10, 10);
                            rich_conter.ForeColor = Color.FromArgb(255, 255, 255);
                            rich_conter.BackColor = Color.FromArgb(0, 122, 204);
                            rich_conter.Dock = DockStyle.Fill;
                            rich_conter.MouseDown += new MouseEventHandler(richconter_MouseClick);
                            rich_conter.Tag = voiceFile;
                            rich_conter.MouseEnter += new EventHandler(Voice_MouseEnter);//图标
                            rich_conter.MouseClick += new System.Windows.Forms.MouseEventHandler(Voice_MouseClick);//点击播放语音
                            rich_conter.ContentsResized += new ContentsResizedEventHandler(rich_ContentsResized);
                            rc.Controls.Add(rich_conter);
                        }
                        else if (msgBody.otherDesc  == "图片")//当为图片的时
                        {
                            //文件路径
                            string url = msgBody.urlPath;//存在两种情况，刷新时和点击发送时:1.刷新时拉去的是https的路径;2.点击发送时，直接是本地盘符地址
                            if (url == "")
                            {
                                return;
                            }
                            string file_name = "";

                            if (url.StartsWith("http:"))//网络图片
                            {
                                file_name = url.Substring(url.LastIndexOf("/") + 1);
                            }
                            else//本机图片
                            {
                                file_name = url.Substring(url.LastIndexOf("\\") + 1);
                            }

                            if (!file_name.ToLower().Contains(".png"))
                            {
                                file_name += ".png";
                            }

                            //因为环信的uri中不包含后缀名,TODO:可能存错格式
                            string download_file = download_file_path + file_name;// + ".png"

                            //如果是本地文件，添加到缓存,下次直接从加载直接从缓存取
                            if (!url.StartsWith("http:"))
                            {
                                File.Copy(url, download_file);
                            }

                            //不存在则下载
                            if (!File.Exists(download_file))
                            {
                                ChatUtility.DownLoadFiles(url, download_file);
                            }

                            //存放临时的宽高
                            int imag_w = 0;
                            int imag_h = 0;

                            //获取宽高
                            using (FileStream fs = new FileStream(download_file, FileMode.Open, FileAccess.Read))
                            {
                                System.Drawing.Image image_temp = System.Drawing.Image.FromStream(fs);
                                imag_w = image_temp.Width;
                                imag_h = image_temp.Height;//或者根据图片真实值设定
                            }

                            //根据图片宽高设置对应缩略图的宽高
                            Linewidth = imag_w > 300 ? 300 : imag_w;
                            Lineheight = imag_h > 300 ? 300 : imag_h;

                            PictureBox send_pic = new PictureBox();
                            send_pic.SizeMode = PictureBoxSizeMode.StretchImage;//图片适应PicBox大小
                            send_pic.Size = new Size(Linewidth, Lineheight);
                            send_pic.Image = Image.FromFile(download_file);
                            Image send_image = send_pic.Image;
                            send_pic.Image = send_image;

                            //添加点击事件
                            send_pic.MouseClick += new System.Windows.Forms.MouseEventHandler(Pic_MouseClick);
                            rc.Controls.Add(send_pic);
                        }
                        else
                        {
                            rich_conter.Rtf = msgBody.rtfStr;//文本
                            rich_conter.WordWrap = true;
                            rich_conter.ReadOnly = true;
                            rich_conter.BorderStyle = BorderStyle.None;
                            rich_conter.ScrollBars = RichTextBoxScrollBars.None;
                            rich_conter.Location = new Point(10, 10);
                            rich_conter.ForeColor = Color.FromArgb(255, 255, 255);
                            rich_conter.BackColor = Color.FromArgb(90, 143, 0);
                            rich_conter.Dock = DockStyle.Fill;
                            rich_conter.MouseDown += new MouseEventHandler(richconter_MouseClick);
                            rich_conter.ContentsResized += new ContentsResizedEventHandler(rich_ContentsResized);
                            rc.Controls.Add(rich_conter);
                        }

                        rc.BackColor = Color.FromArgb(90, 143, 0);
                        rc.Width = Linewidth;
                        rc.Height = Lineheight;
                        rc.Location = new Point(10, 10);

                        conter_panel.BackColor = Color.FromArgb(90, 143, 0);
                        conter_panel.Width = Linewidth + 25;
                        conter_panel.Height = Lineheight + 20;
                        conter_panel.Location = new Point(540 - conter_panel.Width, 30);//和hard_img坐标位置同步修改
                        Bitmap localBitmap = new Bitmap(conter_panel.Width, conter_panel.Height);
                        Graphics bitmapGraphics = Graphics.FromImage(localBitmap);
                        bitmapGraphics.Clear(BackColor);
                        bitmapGraphics.SmoothingMode = SmoothingMode.AntiAlias;
                        Draw(conter_panel.ClientRectangle, bitmapGraphics, 18, true, 0, Color.FromArgb(90, 143, 0), Color.FromArgb(90, 143, 0));
                        conter_panel.BackgroundImage = localBitmap;
                        conter_panel.Controls.Add(rc);
                    }
                    else
                    {

                        hard_img.Size = new Size(64, 64);
                        hard_img.Image = Image.FromFile(@"Resources\BBGJ_Chat.png");
                        Image image = hard_img.Image;
                        //Image newImage = CutEllipse(image, new Rectangle(0, 0, 200, 200), new Size(64, 64));
                        hard_img.Image = image;
                        hard_img.Location = new Point(0, 17);

                        //时间位置
                        //u_name.Location = new Point(0, 0);
                        u_name.Location = new Point(0, 0);
                        u_name.TextAlign = ContentAlignment.MiddleLeft;

                        if (msgBody.otherDesc  == "语音")//当为音频时
                        {
                            string voicePath = @"sdkdata\appdata\" + msgBody.loginUser + "\\" + msgBody.currentChat;
                            //语音SDK自动缓存路径为：sdkdata\appdata\8226\000049\音频.mp3
                            //文件路径
                            string url = msgBody.urlPath;
                            if (url == "")
                            {
                                return;
                            }

                            //获取音频文件名
                            string file_name = url.Substring(url.LastIndexOf("/") + 1);
                            if (!file_name.ToLower().Contains(".mp3"))
                            {
                                file_name += ".mp3";
                            }

                            //音频文件路径
                            string voiceFile = voicePath + "\\" + file_name;

                            //不存在则下载
                            if (!File.Exists(voiceFile))
                            {
                                ChatUtility.DownLoadFiles(url, voiceFile);
                            }

                            string mp3Times = ChatUtility.getMp3Times(voiceFile);
                            string content = "语音消息 " + mp3Times + "″" + ")))";
                            rich_conter.Rtf = ChatUtility.str2Rtf(content);
                            rich_conter.Cursor = Cursors.Hand;
                           ChatUtility.Calc_PanelWidth(msgBody.rtfStr,out Linewidth, out Lineheight);

                            rich_conter.WordWrap = true;
                            rich_conter.ReadOnly = true;
                            rich_conter.BorderStyle = BorderStyle.None;
                            rich_conter.ScrollBars = RichTextBoxScrollBars.None;
                            rich_conter.Location = new Point(10, 10);
                            rich_conter.ForeColor = Color.FromArgb(255, 255, 255);
                            rich_conter.BackColor = Color.FromArgb(0, 122, 204);
                            rich_conter.Dock = DockStyle.Fill;
                            rich_conter.MouseDown += new MouseEventHandler(richconter_MouseClick);
                            rich_conter.Tag = voiceFile;
                            rich_conter.MouseEnter += new EventHandler(Voice_MouseEnter);//图标
                            rich_conter.MouseClick += new System.Windows.Forms.MouseEventHandler(Voice_MouseClick);//点击播放语音
                            rich_conter.ContentsResized += new ContentsResizedEventHandler(rich_ContentsResized);
                            rc.Controls.Add(rich_conter);
                        }
                        else if (msgBody.otherDesc  == "图片")//当为图片的时
                        {

                            //文件路径
                            string url = msgBody.urlPath;
                            if (url == "")
                            {
                                return;
                            }
                            //LogHelper.Log("url:", url);
                            string file_name = url.Substring(url.LastIndexOf("/") + 1);
                            //LogHelper.Log("file_name:", file_name);
                            if (!file_name.ToLower().Contains(".png"))
                            {
                                file_name += ".png";
                            }

                            //因为环信的uri中不包含后缀名
                            string download_file = download_file_path + file_name;
                            //LogHelper.Log("download_file:", download_file);
                            //不存在则下载
                            if (!File.Exists(download_file))
                            {
                                ChatUtility.DownLoadFiles(url, download_file);
                            }

                            //存放临时的宽高
                            int imag_w = 0;
                            int imag_h = 0;

                            //获取宽高
                            using (FileStream fs = new FileStream(download_file, FileMode.Open, FileAccess.Read))
                            {
                                //LogHelper.Log("获取宽高:", "开始");
                                System.Drawing.Image image_temp = System.Drawing.Image.FromStream(fs);
                                imag_w = image_temp.Width;
                                imag_h = image_temp.Height;//或者根据图片真实值设定
                                //LogHelper.Log("获取宽高:", "结束");
                            }

                            //根据图片宽高设置对应缩略图的宽高
                            Linewidth = imag_w > 300 ? 300 : imag_w;
                            Lineheight = imag_h > 300 ? 300 : imag_h;

                            PictureBox receive_pic = new PictureBox();
                            receive_pic.SizeMode = PictureBoxSizeMode.StretchImage;//图片适应PicBox大小
                            receive_pic.Size = new Size(Linewidth, Lineheight);
                            receive_pic.Image = Image.FromFile(download_file);
                            Image receive_image = receive_pic.Image;
                            receive_pic.Image = receive_image;
                            //添加点击事件
                            receive_pic.MouseClick += new System.Windows.Forms.MouseEventHandler(Pic_MouseClick);
                            rc.Controls.Add(receive_pic);
                        }
                        else//为文字时
                        {
                            rich_conter.Rtf = msgBody.rtfStr;
                            rich_conter.WordWrap = true;
                            rich_conter.ReadOnly = true;
                            rich_conter.BorderStyle = BorderStyle.None;
                            rich_conter.ScrollBars = RichTextBoxScrollBars.None;
                            rich_conter.Location = new Point(10, 10);
                            rich_conter.ForeColor = Color.FromArgb(255, 255, 255);
                            rich_conter.BackColor = Color.FromArgb(0, 122, 204);
                            rich_conter.Dock = DockStyle.Fill;
                            rich_conter.MouseDown += new MouseEventHandler(richconter_MouseClick);
                            rich_conter.ContentsResized += new ContentsResizedEventHandler(rich_ContentsResized);
                            rc.Controls.Add(rich_conter);
                        }

                        rc.BackColor = Color.FromArgb(0, 122, 204);
                        rc.Width = Linewidth;
                        rc.Height = Lineheight;
                        rc.Location = new Point(20, 10);

                        conter_panel.BackColor = Color.FromArgb(0, 122, 204);
                        conter_panel.Width = Linewidth + 35;
                        conter_panel.Height = Lineheight + 20;
                        conter_panel.Controls.Add(rc);
                        conter_panel.Location = new Point(70, 30);
                        Bitmap localBitmap = new Bitmap(conter_panel.Width, conter_panel.Height);
                        Graphics bitmapGraphics = Graphics.FromImage(localBitmap);
                        bitmapGraphics.Clear(BackColor);
                        bitmapGraphics.SmoothingMode = SmoothingMode.AntiAlias;
                        Draw(conter_panel.ClientRectangle, bitmapGraphics, 18, true, 1, Color.FromArgb(0, 122, 204), Color.FromArgb(0, 122, 204));
                        conter_panel.BackgroundImage = localBitmap;
                        conter_panel.Controls.Add(rc);
                    }

                    uTake.Controls.Add(hard_img);
                    uTake.Controls.Add(u_name);
                    uTake.Controls.Add(conter_panel);
                    uTake.AutoSize = true;
                    uTake.Dock = DockStyle.Top;

                    uTake.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    hard_img.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    u_name.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    conter_panel.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    rich_conter.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    rc.MouseWheel += new MouseEventHandler(c_OnMouseWheel);

                    Showinfo_panel.Controls.Add(uTake);
                    Showinfo_panel.AutoSize = true;//自适应大小

                    //计算滑动高度
                    climt += uTake.Height;
                }

            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-HandleRecordMessage:", ex.Message);
                 
            }
        }

        /// <summary>
        /// 根据收发处理信息
        /// </summary>
        /// <param name="msgBody"></param>
        private void HandleMessage(MsgBody msgBody)
        {
            try
            {

                //计算内容所占的宽度
                if (msgBody.otherDesc  == "")//文本
                {
                    ChatUtility.Calc_PanelWidth(msgBody.rtfStr,out Linewidth, out Lineheight);
                }
                else if (msgBody.otherDesc  == "图片")// 计算图片的长宽
                {
                    Linewidth = 300;
                    Lineheight = 300;//或者根据图片真实值设定
                }
                else if (msgBody.otherDesc  == "语音")
                {
                    //根据文本值，设置统一的长度和高度
                }

                //是否当前模块
                if (msgBody.chanelId == Chanel.ToString())
                {
                    Panel uTake = new Panel();
                    PictureBox hard_img = new PictureBox();
                    Label u_name = new Label();
                    Panel conter_panel = new Panel();
                    Panel rc = new Panel();
                    //使用改变的PicRichTextBox，为背景透明
                    RichTextBoxEx rich_conter = new RichTextBoxEx();

                    if (msgBody.currentChat.Length >= 15)
                    {
                        if (msgBody.direction == "SEND")
                        {
                            //u_name.Text =msgBody.serverTime + " (" + msgBody.messageFrom + ") "+ (dicGroupMembers[msgBody.currentChat][msgBody.messageFrom]).NickName; //时间 + （用户） + 姓名

                            u_name.Text = msgBody.serverTime + " (" + msgBody.messageFrom + ") 调度员" ; //时间 + （用户） + 姓名
                        }
                        else
                        {
                            //u_name.Text = (dicGroupMembers[msgBody.currentChat][msgBody.messageFrom]).NickName + " (" + msgBody.messageFrom + ") " + msgBody.serverTime; //姓名 +（用户） + 时间

                            u_name.Text = "调度员 (" + msgBody.messageFrom + ") " + msgBody.serverTime; //姓名 +（用户） + 时间
                        }

                    }
                    else
                    {
                        u_name.Text = msgBody.serverTime;//时间
                    }
                 
                    //u_name.AutoSize = true;
                    u_name.Height = 17;
                    u_name.Width = 225;
                    //u_name.ForeColor = Color.FromArgb(195, 195, 195);
                    //u_name.ForeColor = Color.FromArgb(77, 77, 255);
                    u_name.ForeColor = Color.FromArgb(47, 12, 247);
                    //判断是否本人，本人右侧显示，其他左侧显示
                    //if (msgBody.loginUser == UserName)
                    if (msgBody.direction == "SEND")
                    {
                        hard_img.Size = new Size(64, 64);
                        hard_img.Image = Image.FromFile(@"Resources\BBGJ_Chat.png");
                        Image image = hard_img.Image;
                        //Image newImage = CutEllipse(image, new Rectangle(0, 0, 200, 200), new Size(64, 64));
                        hard_img.Image = image;
                        hard_img.Location = new Point(550, 17);

                        //聊天天记录的时间位置
                        u_name.Location = new Point(410, 0);
                        u_name.TextAlign = ContentAlignment.MiddleRight;

                        if (msgBody.otherDesc  == "语音")//当为音频时
                        {
                            string voicePath = @"sdkdata\appdata\" + msgBody.loginUser + "\\" + msgBody.currentChat;
                            //语音SDK自动缓存路径为：sdkdata\appdata\8226\000049\音频.mp3
                            //文件路径
                            string url = msgBody.urlPath;
                            if (url == "")
                            {
                                return;
                            }

                            //获取音频文件名
                            string file_name = url.Substring(url.LastIndexOf("/") + 1);
                            if (!file_name.ToLower().Contains(".mp3"))
                            {
                                file_name += ".mp3";
                            }

                            //音频文件路径
                            string voiceFile = voicePath + "\\" + file_name;

                            //不存在则下载
                            if (!File.Exists(voiceFile))
                            {
                                ChatUtility.DownLoadFiles(url, voiceFile);
                            }

                            string mp3Times = ChatUtility.getMp3Times(voiceFile);
                            string content = "语音消息 " + mp3Times + "″" + ")))";
                            rich_conter.Rtf = ChatUtility.str2Rtf(content);
                            rich_conter.Cursor = Cursors.Hand;
                            ChatUtility.Calc_PanelWidth(msgBody.rtfStr,out Linewidth, out Lineheight);

                            rich_conter.WordWrap = true;
                            rich_conter.ReadOnly = true;
                            rich_conter.BorderStyle = BorderStyle.None;
                            rich_conter.ScrollBars = RichTextBoxScrollBars.None;
                            rich_conter.Location = new Point(10, 10);
                            rich_conter.ForeColor = Color.FromArgb(255, 255, 255);
                            rich_conter.BackColor = Color.FromArgb(0, 122, 204);
                            rich_conter.Dock = DockStyle.Fill;
                            rich_conter.MouseDown += new MouseEventHandler(richconter_MouseClick);
                            rich_conter.Tag = voiceFile;
                            rich_conter.MouseEnter += new EventHandler(Voice_MouseEnter);//图标
                            rich_conter.MouseClick += new System.Windows.Forms.MouseEventHandler(Voice_MouseClick);//点击播放语音
                            rich_conter.ContentsResized += new ContentsResizedEventHandler(rich_ContentsResized);
                            rc.Controls.Add(rich_conter);
                        }
                        else if (msgBody.otherDesc  == "图片")//当为图片的时
                        {
                            //文件路径
                            string url = msgBody.urlPath;//存在两种情况，刷新时和点击发送时，刷新时拉去的是https的路径;点击发送时，直接是本地盘符地址
                            if (url == "")
                            {
                                return;
                            }
                            string file_name = "";

                            if (url.StartsWith("http:"))//网络图片
                            {
                                file_name = url.Substring(url.LastIndexOf("/") + 1);
                                //不带后缀
                                if (!file_name.ToLower().Contains(".png"))
                                {
                                    file_name += ".png";
                                }
                            }
                            else//本机图片
                            {
                                file_name = url.Substring(url.LastIndexOf("\\") + 1);//本机图片有后缀
                            }

                            //因为环信的uri中不包含后缀名
                            string download_file = download_file_path + file_name;// + ".png"

                            //如果是本地文件，添加到缓存
                            if (!url.StartsWith("http:"))
                            {
                                if (!File.Exists(download_file))
                                {
                                    File.Copy(url, download_file);
                                }
                            }

                            //不存在则下载
                            if (!File.Exists(download_file))
                            {
                                ChatUtility.DownLoadFiles(url, download_file);
                            }

                            //存放临时的宽高
                            int imag_w = 0;
                            int imag_h = 0;

                            //获取宽高
                            using (FileStream fs = new FileStream(download_file, FileMode.Open, FileAccess.Read))
                            {
                                System.Drawing.Image image_temp = System.Drawing.Image.FromStream(fs);
                                imag_w = image_temp.Width;
                                imag_h = image_temp.Height;//或者根据图片真实值设定
                            }

                            //根据图片宽高设置对应缩略图的宽高
                            Linewidth = imag_w > 300 ? 300 : imag_w;
                            Lineheight = imag_h > 300 ? 300 : imag_h;

                            PictureBox send_pic = new PictureBox();
                            send_pic.SizeMode = PictureBoxSizeMode.StretchImage;//图片适应PicBox大小
                            send_pic.Size = new Size(Linewidth, Lineheight);
                            send_pic.Image = Image.FromFile(download_file);
                            Image send_image = send_pic.Image;
                            send_pic.Image = send_image;

                            //添加点击事件
                            send_pic.MouseClick += new System.Windows.Forms.MouseEventHandler(Pic_MouseClick);
                            rc.Controls.Add(send_pic);
                        }
                        else
                        {
                            rich_conter.Rtf = msgBody.rtfStr;
                            rich_conter.WordWrap = true;
                            rich_conter.ReadOnly = true;
                            rich_conter.BorderStyle = BorderStyle.None;
                            rich_conter.ScrollBars = RichTextBoxScrollBars.None;
                            rich_conter.Location = new Point(10, 10);
                            rich_conter.ForeColor = Color.FromArgb(255, 255, 255);
                            rich_conter.BackColor = Color.FromArgb(90, 143, 0);
                            rich_conter.Dock = DockStyle.Fill;
                            rich_conter.MouseDown += new MouseEventHandler(richconter_MouseClick);
                            rich_conter.ContentsResized += new ContentsResizedEventHandler(rich_ContentsResized);
                            rc.Controls.Add(rich_conter);
                        }

                        rc.BackColor = Color.FromArgb(90, 143, 0);
                        rc.Width = Linewidth;
                        rc.Height = Lineheight;
                        rc.Location = new Point(10, 10);

                        conter_panel.BackColor = Color.FromArgb(90, 143, 0);
                        conter_panel.Width = Linewidth + 25;
                        conter_panel.Height = Lineheight + 20;
                        conter_panel.Location = new Point(540 - conter_panel.Width, 30);//和hard_img坐标位置同步修改
                        Bitmap localBitmap = new Bitmap(conter_panel.Width, conter_panel.Height);
                        Graphics bitmapGraphics = Graphics.FromImage(localBitmap);
                        bitmapGraphics.Clear(BackColor);
                        bitmapGraphics.SmoothingMode = SmoothingMode.AntiAlias;
                        Draw(conter_panel.ClientRectangle, bitmapGraphics, 18, true, 0, Color.FromArgb(90, 143, 0), Color.FromArgb(90, 143, 0));
                        conter_panel.BackgroundImage = localBitmap;
                        conter_panel.Controls.Add(rc);
                    }
                    else
                    {

                        hard_img.Size = new Size(64, 64);
                        hard_img.Image = Image.FromFile(@"Resources\BBGJ_Chat.png");
                        Image image = hard_img.Image;
                        //Image newImage = CutEllipse(image, new Rectangle(0, 0, 200, 200), new Size(64, 64));
                        hard_img.Image = image;
                        hard_img.Location = new Point(0, 17);

                        //设置聊天记录时间的位置
                        u_name.Location = new Point(0, 0);
                        u_name.TextAlign = ContentAlignment.MiddleLeft;

                        if (msgBody.otherDesc  == "语音")//当为音频时
                        {
                            string voicePath = @"sdkdata\appdata\" + msgBody.loginUser + "\\" + msgBody.currentChat;
                            //语音SDK自动缓存路径为：sdkdata\appdata\8226\000049\音频.mp3
                            //文件路径
                            string url = msgBody.urlPath;
                            if (url == "")
                            {
                                return;
                            }

                            //获取音频文件名
                            string file_name = url.Substring(url.LastIndexOf("/") + 1);
                            if (!file_name.ToLower().Contains(".mp3"))
                            {
                                file_name += ".mp3";
                            }

                            //音频文件路径
                            string voiceFile = voicePath + file_name;

                            //不存在则下载
                            if (!File.Exists(voiceFile))
                            {
                                ChatUtility.DownLoadFiles(url, voiceFile);
                            }

                            string mp3Times = ChatUtility.getMp3Times(voiceFile);
                            string content = "语音消息 " + mp3Times + "″" + ")))";
                            rich_conter.Rtf = ChatUtility.str2Rtf(content);
                            rich_conter.Cursor = Cursors.Hand;
                           ChatUtility.Calc_PanelWidth(msgBody.rtfStr,out Linewidth, out Lineheight);

                            rich_conter.WordWrap = true;
                            rich_conter.ReadOnly = true;
                            rich_conter.BorderStyle = BorderStyle.None;
                            rich_conter.ScrollBars = RichTextBoxScrollBars.None;
                            rich_conter.Location = new Point(10, 10);
                            rich_conter.ForeColor = Color.FromArgb(255, 255, 255);
                            rich_conter.BackColor = Color.FromArgb(0, 122, 204);
                            rich_conter.Dock = DockStyle.Fill;
                            rich_conter.MouseDown += new MouseEventHandler(richconter_MouseClick);
                            rich_conter.Tag = voiceFile;
                            rich_conter.MouseEnter += new EventHandler(Voice_MouseEnter);//图标
                            rich_conter.MouseClick += new System.Windows.Forms.MouseEventHandler(Voice_MouseClick);//点击播放语音
                            rich_conter.ContentsResized += new ContentsResizedEventHandler(rich_ContentsResized);
                            rc.Controls.Add(rich_conter);
                        }
                        else if (msgBody.otherDesc  == "图片")//当为图片的时
                        {
                            //文件路径
                            string url = msgBody.urlPath;
                            if (url == "")
                            {
                                return;
                            }
                            string file_name = url.Substring(url.LastIndexOf("/") + 1);
                            if (!file_name.ToLower().Contains(".png"))
                            {
                                file_name += ".png";
                            }

                            //因为环信的uri中不包含后缀名
                            string download_file = download_file_path + file_name;// + ".png"

                            //不存在则下载
                            if (!File.Exists(download_file))
                            {
                                ChatUtility.DownLoadFiles(url, download_file);
                            }

                            //存放临时的宽高
                            int imag_w = 0;
                            int imag_h = 0;

                            //获取宽高
                            using (FileStream fs = new FileStream(download_file, FileMode.Open, FileAccess.Read))
                            {
                                System.Drawing.Image image_temp = System.Drawing.Image.FromStream(fs);
                                imag_w = image_temp.Width;
                                imag_h = image_temp.Height;//或者根据图片真实值设定
                            }

                            //根据图片宽高设置对应缩略图的宽高
                            Linewidth = imag_w > 300 ? 300 : imag_w;
                            Lineheight = imag_h > 300 ? 300 : imag_h;

                            PictureBox receive_pic = new PictureBox();
                            receive_pic.SizeMode = PictureBoxSizeMode.StretchImage;//图片适应PicBox大小
                            receive_pic.Size = new Size(Linewidth, Lineheight);
                            receive_pic.Image = Image.FromFile(download_file);
                            Image receive_image = receive_pic.Image;
                            receive_pic.Image = receive_image;
                            //添加点击事件
                            receive_pic.MouseClick += new System.Windows.Forms.MouseEventHandler(Pic_MouseClick);
                            rc.Controls.Add(receive_pic);
                        }
                        else//为文字时
                        {
                            rich_conter.Rtf = msgBody.rtfStr;
                            rich_conter.WordWrap = true;
                            rich_conter.ReadOnly = true;
                            rich_conter.BorderStyle = BorderStyle.None;
                            rich_conter.ScrollBars = RichTextBoxScrollBars.None;
                            rich_conter.Location = new Point(10, 10);
                            rich_conter.ForeColor = Color.FromArgb(255, 255, 255);
                            rich_conter.BackColor = Color.FromArgb(0, 122, 204);
                            rich_conter.Dock = DockStyle.Fill;
                            rich_conter.MouseDown += new MouseEventHandler(richconter_MouseClick);
                            rich_conter.ContentsResized += new ContentsResizedEventHandler(rich_ContentsResized);
                            rc.Controls.Add(rich_conter);
                        }

                        rc.BackColor = Color.FromArgb(0, 122, 204);
                        rc.Width = Linewidth;
                        rc.Height = Lineheight;
                        rc.Location = new Point(20, 10);

                        conter_panel.BackColor = Color.FromArgb(0, 122, 204);
                        conter_panel.Width = Linewidth + 35;
                        conter_panel.Height = Lineheight + 20;
                        conter_panel.Controls.Add(rc);
                        conter_panel.Location = new Point(70, 30);
                        Bitmap localBitmap = new Bitmap(conter_panel.Width, conter_panel.Height);
                        Graphics bitmapGraphics = Graphics.FromImage(localBitmap);
                        bitmapGraphics.Clear(BackColor);
                        bitmapGraphics.SmoothingMode = SmoothingMode.AntiAlias;
                        Draw(conter_panel.ClientRectangle, bitmapGraphics, 18, true, 1, Color.FromArgb(0, 122, 204), Color.FromArgb(0, 122, 204));
                        conter_panel.BackgroundImage = localBitmap;
                        conter_panel.Controls.Add(rc);
                    }

                    uTake.Controls.Add(hard_img);
                    uTake.Controls.Add(u_name);
                    uTake.Controls.Add(conter_panel);
                    uTake.AutoSize = true;
                    uTake.Dock = DockStyle.Top;

                    uTake.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    hard_img.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    u_name.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    conter_panel.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    rich_conter.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    rc.MouseWheel += new MouseEventHandler(c_OnMouseWheel);

                    Showinfo_panel.Controls.Add(uTake);

                    Showinfo_panel.AutoSize = true;//自适应大小
                    if (Showinfo_panel.Height >= Takeconter_panel.Height)
                    {
                        Showinfo_panel.Top = Takeconter_panel.Height - Showinfo_panel.Height;
                    }
                    rich_conter.Focus();
                    Rich_Edit.Focus();

                    //计算滑动高度
                    climt += uTake.Height;
                }

                cCalc_Scroll();

                if (Showinfo_panel.Height >= Takeconter_panel.Height)
                {
                    TakeScrollHard_panel.Location = new Point(cset_x, climt);
                    cmouse_Wheel = true;
                }

            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-HandleMessage:", ex.Message);    
            }
        }
        #endregion

        #region 界面定位最新聊天记录

        //定位聊天界面底部
        private void NavigateToBottom()
        {
            try
            {
                if (Showinfo_panel.Height >= Takeconter_panel.Height)//当内容一屏幕显示不完
                {
                    TakeScrollHard_panel.Location = new Point(cset_x, climt);
                    cmouse_Wheel = true;
                    Showinfo_panel.Top = Takeconter_panel.Height - Showinfo_panel.Height;
                    Rich_Edit.Focus();
                }
                else//不满一屏幕时
                {
                    TakeScrollHard_panel.Location = new Point(cset_x, 0);
                    Showinfo_panel.Top = 0;
                    Rich_Edit.Focus();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-NavigateToBottom:", ex.Message);
            }
           
        }

        #endregion

        #endregion
        
        #region 接口实现方法
        public void OnMessagesReceived(List<AgoraChat.Message> messages)
        {
            try
            {
                load_f = false;
                //根据
                foreach (AgoraChat.Message message in messages)
                {
                    string from = message.From;
                    //转为文本
                    var TextBody = message.Body as AgoraChat.MessageBody.TextBody;
                    var txtInfo = TextBody?.Text;

                    //转为图片
                    var ImageBody = message.Body as AgoraChat.MessageBody.ImageBody;

                    //转为语音
                    var VoiceBody = message.Body as AgoraChat.MessageBody.VoiceBody;
                    if (message.MessageType == MessageType.Chat)
                    {
                        if (!dicUnread.ContainsKey(from))
                        {
                            dicUnread.Add(from,"好友");
                        }

                        //从from转Chanel值，方便对好友列表操作界面
                        int tempChanel = dic.FirstOrDefault(s => s.Value == from).Key;
                        //如果没有，则添加
                        if (!ht.ContainsKey(tempChanel))
                        {
                            ht.Add(tempChanel, from);
                        }

                        //判断弹窗提示内容
                        if (string.IsNullOrEmpty(txtInfo))
                        {
                            if (ImageBody != null)
                            {
                                txtInfo = "图片消息";
                                //全局变量存储当前图片的路径
                                receiveImagePath = ImageBody.RemotePath.ToString();
                            }
                            else
                            {
                                if (VoiceBody != null)
                                {
                                    txtInfo = "语音消息";
                                    //全局变量存储当前图片的路径
                                    receiveVoicePath = VoiceBody.RemotePath.ToString();
                                }
                            }
                        }

                        //弹窗提示
                        _mainHandleIntPtr.BeginInvoke(updateTxt, from, txtInfo);

                        //是否窗口打开
                        if (Chanel2_Info.Visible)
                        {
                            //打开好友栏
                            if (currentChatUser.Length >= 15)
                            {
                                //更新界面
                                this.Invoke(new InvokeHandler(delegate ()
                                {
                                    Chanel_panel2_MouseClick(null, null);
                                })); 
                            }

                            //判断发送者是否和当前聊天用户一致，是则更新聊天内容，不弹窗
                            if (from == currentChatUser)
                            {
                                //更新聊天内容
                                string timeTick = message.ServerTime.ToString();
                              MsgBody msgBody = new MsgBody();
                                msgBody.direction = "RECEIVE";//SEND  &&  RECEIVE
                                msgBody.currentChat = from;
                                msgBody.chanelId = Chanel.ToString();//当前好友index
                                msgBody.loginUser = UserName;//根据消息体中值获取
                                msgBody.serverTime = ChatUtility.getTimeByMillsSpan(timeTick);
                                msgBody.messageFrom = from;

                                if (TextBody != null)//发送的为文本
                                {
                                    msgBody.urlPath = "";
                                    msgBody.rtfStr = ChatUtility.str2Rtf(txtInfo);
                                    msgBody.otherDesc = "";
                                }
                                else//发送的为图片、音频
                                {
                                    if (ImageBody != null)
                                    {
                                        if (string.IsNullOrEmpty(receiveImagePath))//路径为空，则跳过
                                        {
                                            continue;
                                        }

                                        msgBody.urlPath = receiveImagePath;
                                        msgBody.rtfStr = "";
                                        msgBody.otherDesc = "图片";
                                    }
                                    else
                                    {
                                        if (VoiceBody != null)
                                        {
                                            if (string.IsNullOrEmpty(receiveVoicePath))//路径为空，则跳过
                                            {
                                                continue;
                                            }

                                            //语音
                                            msgBody.urlPath = receiveVoicePath;
                                            msgBody.rtfStr = ChatUtility.str2Rtf("语音:)))");
                                            msgBody.otherDesc = "语音";
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                }

                                //up_count不等于1，则重新加载聊天记录，回到聊天底部，追加聊天记录,再更新内存消息
                                if (up_count != 1)
                                {
                                    //当前聊天界面
                                    this.Showinfo_panel.Controls.Clear();
                                    this.Showinfo_panel.Size = new Size(557, 46);//聊天界面大小
                                    climt = -TakeScrollHard_panel.Height;

                                    //重置上下翻页数
                                    up_count = 1;
                                    down_count = 0;
                                    //下10条标签隐藏
                                    lb_down.Visible = false;
                                    //重新获取近10条聊天记录
                                    getChatRecord(currentChatUser);//处理数据
                                }
                                else//直接追加
                                {
                                    if (ht.ContainsKey(tempChanel))
                                    {
                                        //更新界面
                                        this.Invoke(new InvokeHandler(delegate ()
                                        {
                                            HandleMessage(msgBody);
                                        }));
                                        //更新内存消息
                                        Totallist.Add(message);
                                        total_count = Totallist.Count;
                                    }

                                }

                                //追加完聊天记录后，移除KEY
                                if (ht.ContainsKey(tempChanel))
                                {
                                    ht.Remove(tempChanel);
                                }
                            }
                            else
                            {
                                //如果不是当前聊天用户，设置提示好友列表颜色，点击时更新去除Key
                                if (ht.ContainsKey(tempChanel))
                                {
                                    //设置当前好友列表背景色
                                    Thread threadSetBgColor = new Thread(new ParameterizedThreadStart(SetBgColor));
                                    threadSetBgColor.Start((dic.Count - 1 - tempChanel));
                                }
                            }
                        }
                    }
                    else if(message.MessageType == MessageType.Group)
                    {
                        string conversationId = message.ConversationId;
                        if (!dicUnread.ContainsKey(conversationId))
                        {
                            dicUnread.Add(conversationId, "群聊");
                        }
                        //从from转Chanel值，方便对好友列表操作界面
                        int tempChanel = dicGroupIds.FirstOrDefault(s => s.Value == conversationId).Key;
                        //如果没有，则添加
                        if (!htGroup.ContainsKey(tempChanel))
                        {
                            htGroup.Add(tempChanel, conversationId);
                        }

                        //判断弹窗提示内容
                        if (string.IsNullOrEmpty(txtInfo))
                        {
                            if (ImageBody != null)
                            {
                                txtInfo = "图片消息";
                                //全局变量存储当前图片的路径
                                receiveImagePath = ImageBody.RemotePath.ToString();

                            }
                            else
                            {
                                if (VoiceBody != null)
                                {
                                    txtInfo = "语音消息";
                                    //全局变量存储当前图片的路径
                                    receiveVoicePath = VoiceBody.RemotePath.ToString();
                                }
                            }
                        }

                        //弹窗提示
                        _mainHandleIntPtr.BeginInvoke(updateTxt, conversationId, txtInfo);

                        //是否窗口打开
                        if (Chanel2_Info.Visible)
                        {
                            //打开群聊栏
                            if (currentChatUser.Length < 12)
                            {
                                //更新界面
                                this.Invoke(new InvokeHandler(delegate ()
                                {
                                    Chanel_panel4_MouseClick(null, null);
                                }));    
                            }
                            //判断发送者是否和当前聊天用户一致，是则更新聊天内容，不弹窗
                            if (conversationId == currentChatUser)
                            {
                                //更新聊天内容
                                string timeTick = message.ServerTime.ToString();
                                MsgBody msgBody = new MsgBody();
                                msgBody.direction = "RECEIVE";//SEND  &&  RECEIVE
                                msgBody.currentChat = conversationId;
                                msgBody.chanelId = Chanel.ToString();//当前好友index
                                msgBody.loginUser = UserName;//根据消息体中值获取
                                msgBody.serverTime = ChatUtility.getTimeByMillsSpan(timeTick);
                                msgBody.messageFrom = from;

                                if (TextBody != null)//发送的为文本
                                {
                                    msgBody.urlPath = "";
                                    msgBody.rtfStr = ChatUtility.str2Rtf(txtInfo);
                                    msgBody.otherDesc = "";
                                }
                                else//发送的为图片、音频
                                {
                                    if (ImageBody != null)
                                    {
                                        if (string.IsNullOrEmpty(receiveImagePath))//路径为空，则跳过
                                        {
                                            continue;
                                        }

                                        msgBody.urlPath = receiveImagePath;
                                        msgBody.rtfStr = "";
                                        msgBody.otherDesc = "图片";
                                    }
                                    else
                                    {
                                        if (VoiceBody != null)
                                        {
                                            if (string.IsNullOrEmpty(receiveVoicePath))//路径为空，则跳过
                                            {
                                                continue;
                                            }

                                            //语音
                                            msgBody.urlPath = receiveVoicePath;
                                            msgBody.rtfStr = ChatUtility.str2Rtf("语音:)))");
                                            msgBody.otherDesc = "语音";
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                }

                                //up_count不等于1，则重新加载聊天记录，回到聊天底部，追加聊天记录,再更新内存消息
                                if (up_count != 1)
                                {
                                    //当前聊天界面
                                    this.Showinfo_panel.Controls.Clear();
                                    this.Showinfo_panel.Size = new Size(557, 46);//聊天界面大小
                                    climt = -TakeScrollHard_panel.Height;

                                    //重置上下翻页数
                                    up_count = 1;
                                    down_count = 0;
                                    //下10条标签隐藏
                                    lb_down.Visible = false;
                                    //重新获取近10条聊天记录
                                    getChatRecord(currentChatUser);//处理数据
                                }
                                else//直接追加
                                {
                                    if (htGroup.ContainsKey(tempChanel))
                                    {
                                        //更新界面
                                        this.Invoke(new InvokeHandler(delegate ()
                                        {
                                            HandleMessage(msgBody);
                                        }));
                                        //更新内存消息
                                        Totallist.Add(message);
                                        total_count = Totallist.Count;
                                    }

                                }

                                //追加完聊天记录后，移除KEY
                                if (htGroup.ContainsKey(tempChanel))
                                {
                                    htGroup.Remove(tempChanel);
                                }
                            }
                            else
                            {//如果不是当前聊天用户，设置提示好友列表颜色，点击时更新去除Key

                                if (htGroup.ContainsKey(tempChanel))
                                {
                                    //设置当前好友列表背景色
                                    Thread threadSetBgColor = new Thread(new ParameterizedThreadStart(SetBgColor));
                                    threadSetBgColor.Start((dicGroupIds.Count - 1 - tempChanel));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log("IM-OnMessagesReceived:", ex.Message);
                 
            }
            
        }


        public void OnGroupMessageRead(List<GroupReadAck> list)
        {
            //throw new NotImplementedException();
        }

        public void OnConversationsUpdate()
        {
            // throw new NotImplementedException();
        }

        public void OnConversationRead(string from, string to)
        {
            //throw new NotImplementedException();
        }

        public void MessageReactionDidChange(List<MessageReactionChange> list)
        {
           // throw new NotImplementedException();
        }

        void IChatManagerDelegate.OnCmdMessagesReceived(List<AgoraChat.Message> messages)
        {
            //throw new NotImplementedException();
        }

        void IChatManagerDelegate.OnMessagesRead(List<AgoraChat.Message> messages)
        {
            //throw new NotImplementedException();
        }

        void IChatManagerDelegate.OnMessagesDelivered(List<AgoraChat.Message> messages)
        {
            //throw new NotImplementedException();
        }

        void IChatManagerDelegate.OnMessagesRecalled(List<AgoraChat.Message> messages)
        {
            //throw new NotImplementedException();
        }
        public void OnReadAckForGroupMessageUpdated()
        {
            //throw new NotImplementedException();
        }
        #endregion

        #region Utility

        /// <summary>
        /// 判断聊天窗口是否已经打开
        /// </summary>
        /// <returns></returns>
        public bool IsOpenChatFrm()
        {
            foreach (Form form in Application.OpenForms)
            {
                if (form.Name == "FrmChatRoom")
                {
                    return true;
                }
            }
            return false;
        }


        /// <summary>
        /// 设置鼠标移动到语音上出现小手图标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Voice_MouseEnter(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Hand;
        }

        /// <summary>
        /// 播放音频,
        /// 1.添加新引用 COM组件的Microsoft Shell Controls And Automation
        /// 2.添加成功，引用中显示的为Shell32.dll，、
        /// 3.设置Shell32.dll的属性为嵌入互操作类型：FALSE
        /// </summary>
        IWavePlayer wavePlayer;
        AudioFileReader audioFileReader;
        private void Voice_MouseClick(object sender, MouseEventArgs e)
        {
            //通过tag取出音频文件路径
            RichTextBoxEx richBox = (RichTextBoxEx)sender;
            string vioce_file = richBox.Tag.ToString();

            Task.Factory.StartNew(() =>
            {
                wavePlayer = new WaveOut();
                audioFileReader = new AudioFileReader(vioce_file);
                wavePlayer.Init(audioFileReader);
                wavePlayer.Play();//播放
            });

        }

        /// <summary>
        /// 刷新列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Id_label_Click(object sender, EventArgs e)
        {
            #region 刷新
            GetAllContacts();

            //重新加载列表
            InitFriendsList();
            InitGroupList();

            //设置背景
            SetDafault();
            //群聊栏背景
            Chanel_panel4.BackColor = Color.FromArgb(245, 245, 245);
            for (int i = 0; i < Chanel_panel4.Controls.Count; i++)
            {
                Chanel_panel4.Controls[i].BackColor = Color.FromArgb(245, 245, 245);
            }
            #endregion
        }

        /// <summary>
        /// 弹窗查看图片大图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Pic_MouseClick(object sender, MouseEventArgs e)
        {
            FrmViewImages fvi = new FrmViewImages();
            //fvi.AutoSize = true;  
            fvi.StartPosition = FormStartPosition.CenterScreen;
            fvi.pictureBox_MaxView(sender, e);
            fvi.Show();
        }

        /// <summary>
        /// 添加群组和好友后刷新列表更新界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btResresh_Click(object sender, EventArgs e)
        {
            #region 刷新
            GetAllContacts();

            //重新加载列表
            InitFriendsList();
            InitGroupList();

            //设置背景
            SetDafault();
            //群聊栏背景
            Chanel_panel4.BackColor = Color.FromArgb(245, 245, 245);
            for (int i = 0; i < Chanel_panel4.Controls.Count; i++)
            {
                Chanel_panel4.Controls[i].BackColor = Color.FromArgb(245, 245, 245);
            }
            #endregion

            #region 测试
            //Conversation conversation = SDKClient.Instance.ChatManager.GetConversation(currentChatUser);
            //ChatSdkClass chatSdkClass = new ChatSdkClass();
            //chatSdkClass.FetchHistoryMessagesFromServer(conversation.Id);
            #endregion


        }
        /// <summary>
        /// 获取群组成员
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="pageSize"></param>
        /// <param name="cursor"></param>
        public void getGroupMembers(string groupId,string groupOwner, int pageSize = 200, string cursor = "")
        {
            SDKClient.Instance.GroupManager.GetGroupMemberListFromServer(groupId, pageSize, cursor,   new ValueCallBack<CursorResult<string>>(
      onSuccess: (result) =>
      {
          var UserList = result.Data;
          UserList.Add(groupOwner);//群聊中获取不到群主成员信息
          //获取UserInfo
          SDKClient.Instance.UserInfoManager.FetchUserInfoByUserId(UserList, new ValueCallBack<Dictionary<string, UserInfo>>(
             onSuccess: (listUserInfo) =>
             {
                 dicGroupMembers.Add(groupId, listUserInfo);

             }, onError: (code, desc) =>
             {
                 LogHelper.Log("IM获取群聊成员信息失败:", code + ":" + desc);
             }));
      },
      onError: (code, desc) =>
      {

      }
        ));
        }

        /// <summary>
        /// 环信功能页面跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Pic_Me_Click(object sender, EventArgs e)
        {
            ChatManageFrom chatManageFrom = new ChatManageFrom(dicGroupMembers);
            Thread.Sleep(1000);
            chatManageFrom.Show();
        }
       
        #endregion

        #region 窗体以及控件事件

        /// <summary>
        /// 窗口Load事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmChatRoom_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;//跨线程检查
            InitFriendsList();
            //InitGroupList();

            //头像旁边昵称设置
            if (!string.IsNullOrWhiteSpace(dicFriendNames[UserName].ToString()))
            {
                Id_label.Text = dicFriendNames[UserName].ToString();//查询到中文姓名则只显示姓名
            }
            else
            {
                //Id_label.Text = "工号:" + UserName;//显示工号
                Id_label.Text = UserName;//显示工号
            }

            //第一次打开聊天窗口时，默认选中第一个好友
            if (dic.Count > 0 && load_f)
            {
                //默认打开好友列表第一个，最多只执行一次
                Take_Chanel_Click((Panel)Chanel2_Info.Controls[dic.Count - 1], new EventArgs());
                load_f = false;
            }

            

        }
        /// <summary>
        /// 关闭窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmChatRoom_FormClosing(object sender, FormClosingEventArgs e)
        {
            #region 重置默认不选择
            //清空选择的列表
            for (int i = 0; i < Chanel2_Info.Controls.Count; i++)
            {
                //设置好友列表背景色
                Chanel2_Info.Controls[i].BackColor = Color.White;
                Chanel2_Info.Controls[i].Controls[0].BackColor = Color.White;
                Chanel2_Info.Controls[i].Controls[1].BackColor = Color.White;
                Chanel2_Info.Controls[i].Controls[2].ForeColor = Color.White;
                //Chanel2_Info.Controls[i].Controls[2].Text = "";//消息提示不重置
            }
            //清空聊天消息
            this.Showinfo_panel.Controls.Clear();
            //进入聊天设置标签可见性
            lb_up.Visible = false;
            lb_down.Visible = false;
            //次数重置
            up_count = 1;
            down_count = 0;
            //选中的下标重置
            OldChanel = -1;
            Chanel = -1;
            Takepalt_label.Text = "";
            #endregion
            //隐藏窗体
            this.Hide();

            //取消关闭窗体
            e.Cancel = true;

            //最小化
            //this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
            //不显示在任务栏
            //this.ShowInTaskbar = false;

            this.Refresh();

        }

        /// <summary>
        /// 编辑框聚焦
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RichEdit_TextChanged(object sender, EventArgs e)
        {
            this.Focus();
            Rich_Edit.Focus();
        }

        private void richconter_MouseClick(object sender, MouseEventArgs e)
        {
            Rich_Edit.Focus();
        }

        /// <summary>
        /// 设置显示信息气泡框高度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rich_ContentsResized(object sender, ContentsResizedEventArgs e)
        {
            Lineheight = e.NewRectangle.Height;
        }

        #endregion

        #region IConnectionDelegate实现

        /// <summary>
        /// 当用户被踢下线时候提醒
        /// </summary>
        public void OnKickedByOtherDevice()
        {
            try
            {
                //弹窗提示
                //_mainHandleIntPtr.BeginInvoke(updateTxt, "登录", "账户被踢下线!");
                MessageBox.Show("环信账户被异地登录被踢下线!", "掉线提示", MessageBoxButtons.YesNo);
                LogHelper.Log("OnKickedByOtherDevice:", "账户被异地登录被踢下线！");
            }
            catch (Exception ex)
            {
                LogHelper.Log("OnKickedByOtherDevice:", ex.Message);
            }
        }
        public void OnConnected()
        {

        }

        public void OnDisconnected()
        {

        }

        public void OnLoggedOtherDevice()
        {
            try
            {
                //弹窗提示
                //_mainHandleIntPtr.BeginInvoke(updateTxt, "登录", "账户被被踢下线!");
                MessageBox.Show("环信账户被异地登录被踢下线!", "掉线提示");
               //LogHelper.Log("OnKickedByOtherDeviced调用:", "账户被异地登录被踢下线！");
            }
            catch (Exception ex)
            {
                LogHelper.Log("OnKickedByOtherDevice异常:", ex.Message);
            }
        }

        public void OnRemovedFromServer()
        {

        }

        public void OnForbidByServer()
        {

        }

        public void OnChangedIMPwd()
        {

        }

        public void OnLoginTooManyDevice()
        {

        }

        public void OnAuthFailed()
        {

        }

        public void OnTokenExpired()
        {

        }

        public void OnTokenWillExpire()
        {

        }
        #endregion

    }
}
